Java Theory
Java Theory
JAVA WORKING:
COMPILED INTERPRETED
SOURCE CODE BYTE CODE MACHINE CODE
JDK: collection of tools used for developing and running Java programs.
JRE: JAVA RUNNING ENVIRONMENT.
➢ It helps in executing programs developed in JAVA.
Class SampleOne
➢ SampleOne: It is a JAVA identifier that specifies the name of the class to be defined.
OPENING BRACES:
➢ Every class definition in JAVA begins with an opening brace “{“ and ends with a matching a
closing brace “}” .
➢ A class definition in C++ ends with a semicolon.
➢ PUBLIC: It is an access specifier that declares the main method as unprotected and therefore
making it accessible to all other classes.
➢ STATIC: It declares this method as one that belongs to the entire class and not a part of any
objects of the class.
➢ The main must always be declared as static since the interpreter uses this method
before any objects are created.
➢ VOID: The type modifier void states that main method does not return any value.
➢ In order to read data from the keyboard, Java has a scanner class.
➢ Scanner class has a lot of members to read the data from the keyboard.
Scanner S = new.Scanner(System.in)
Int a = S.nextInt();
String = s.nextline();
Char c = s.next().charAt(0);
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
volatile While
Variables in Java
Variable in Java is a data container that saves the data values during Java
program execution. Every variable is assigned a data type that designates
the type and quantity of value it can hold. A variable is a memory location
name for the data.
A variable is a name given to a memory location. It is the basic unit of
storage in a program.
• The value stored in a variable can be changed during program
execution.
• A variable is only a name given to a memory location. All the
operations done on the variable affect that memory location.
• In Java, all variables must be declared before use.
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
• These variables are created when the block is entered, or the
function is called and destroyed after exiting from the block or when
the call returns from the function.
• The scope of these variables exists only within the block in which
the variables are declared, i.e., we can access these variables only
within that block.
2. Instance Variables
Instance variables are non-static variables and are declared in a class
outside of any method, constructor, or block.
• As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when
the object is destroyed.
• Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier, then the default
access specifier will be used.
Java provides many types of operators which can be used according to the
need. They are classified based on the functionality they provide. Some of
the types are:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
1. Arithmetic Operators: They are used to perform simple arithmetic
operations on primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
2. Unary Operators: Unary operators need only one operand. They are
used to increment, decrement or negate a value.
• – : Unary minus, used for negating the values.
• + : Unary plus indicates the positive value (numbers are positive
without this, however). It performs an automatic conversion to int
when the type of its operand is the byte, char, or short. This is
called unary numeric promotion.
• ++ : Increment operator, used for incrementing the value by 1.
There are two varieties of increment operators.
• Post-Increment: Value is first used for computing the
result and then incremented.
• Pre-Increment: Value is incremented first, and then the
result is computed.
• — : Decrement operator, used for decrementing the value by 1.
There are two varieties of decrement operators.
• Post-decrement: Value is first used for computing the
result and then decremented.
• Pre-Decrement: Value is decremented first, and then the
result is computed.
• ! : Logical not operator, used for inverting a boolean value.
3. Assignment Operator: ‘=’ Assignment operator is used to assigning a
value to any variable. It has a right to left associativity, i.e. value given on the
right-hand side of the operator is assigned to the variable on the left, and
therefore right-hand side value must be declared before using it or should be
a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other
operators to build a shorter version of the statement called a Compound
Statement. For example, instead of a = a+5, we can write a += 5.
• +=, for adding left operand with right operand and then assigning it
to the variable on the left.
• -=, for subtracting right operand from left operand and then
assigning it to the variable on the left.
• *=, for multiplying left operand with right operand and then
assigning it to the variable on the left.
• /=, for dividing left operand by right operand and then assigning it to
the variable on the left.
• %=, for assigning modulo of left operand by right operand and then
assigning it to the variable on the left.
4. Relational Operators: These operators are used to check for relations
like equality, greater than, and less than. They return boolean results after
the comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is,
variable relation_operator value
• Some of the relational operators are-
• ==, Equal to returns true if the left-hand side is equal to
the right-hand side.
• !=, Not Equal to returns true if the left-hand side is not
equal to the right-hand side.
• <, less than: returns true if the left-hand side is less than
the right-hand side.
• <=, less than or equal to returns true if the left-hand side
is less than or equal to the right-hand side.
• >, Greater than: returns true if the left-hand side is
greater than the right-hand side.
• >=, Greater than or equal to returns true if the left-hand
side is greater than or equal to the right-hand side.
5. Logical Operators: These operators are used to perform “logical AND”
and “logical OR” operations, i.e., a function similar to AND gate and OR gate
in digital electronics. One thing to keep in mind is the second condition is not
evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has
“Logical NOT”, which returns true when the condition is false and vice-versa
Conditional operators are:
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-
versa
ata types are different sizes and values that can be stored in the variable that
is made as per convenience and circumstances to cover up all test cases.
Also, let us cover up other important ailments that there are majorly two types
of languages that are as follows:
1. First, one is a Statically typed language where each variable and
expression type is already known at compile time. Once a variable is
declared to be of a certain data type, it cannot hold values of other
data types. For example C, C++, Java.
2. The other is Dynamically typed languages. These languages can
receive different data types over time. For example Ruby, Python
Java is statically typed and also a strongly typed language because, in
Java, each type of data (such as integer, character, hexadecimal, packed
decimal, and so forth) is predefined as part of the programming language and
all constants or variables defined for a given program must be described with
one of the data types.
Primitive data are only single values and have no special capabilities. There
are 8 primitive data types. They are depicted below in tabular format below
as follows:
Let us discuss and implement each one of the following data types that are
as follows:
Type 1: boolean
Boolean data type represents only one bit of information either true or
false which is intended to represent the two truth values of logic and
Boolean algebra, but the size of the boolean data type is virtual machine-
dependent. Values of type boolean are not converted implicitly or explicitly
(with casts) to any other type. But the programmer can easily write
conversion code.
Syntax:
boolean booleanVar;
Size: Virtual machine dependent
Values: Boolean such as true, false
Default Value: false
Example:
• Java
// Java Program to Demonstrate Boolean Primitive DataType
// Class
class GFG {
boolean a = false;
boolean b = true;
// If condition holds
if (b == true){
// Print statement
System.out.println("Hi Geek");
// If condition holds
if(a == false){
// Print statement
System.out.println("Hello Geek");
Output
Hi Geek
Hello Geek
Type 2: byte
The byte data type is an 8-bit signed two’s complement integer. The byte
data type is useful for saving memory in large arrays.
Syntax:
byte byteVar;
Size: 1 byte (8 bits)
Values: -128 to 127
Default Value: 0
Example:
• Java
// Java Program to demonstrate Byte Data Type
// Class
class GFG {
byte a = 126;
System.out.println(a);
a++;
System.out.println(a);
a++;
System.out.println(a);
a++;
System.out.println(a);
Output
126
127
-128
-127
Type 3: short
The short data type is a 16-bit signed two’s complement integer. Similar to
byte, use a short to save memory in large arrays, in situations where the
memory savings actually matters.
Syntax:
short shortVar;
Size: 2 byte (16 bits)
Values: -32, 768 to 32, 767 (inclusive)
Default Value: 0
Type 4: int
It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;
Size: 4 byte ( 32 bits )
Values: -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)
Note: The default value is ‘0’
Remember: In Java SE 8 and later, we can use the int data type to
represent an unsigned 32-bit integer, which has a value in the range [0, 232-
1]. Use the Integer class to use the int data type as an unsigned integer.
Type 5: long
The range of a long is quite large. The long data type is a 64-bit two’s
complement integer and is useful for those occasions where an int type is
not large enough to hold the desired value.
Syntax:
long longVar;
Size: 8 byte (64 bits)
Values: {-9, 223, 372, 036, 854, 775, 808} to {9, 223, 372, 036, 854, 775,
807} (inclusive)
Note: The default value is ‘0’.
Remember: In Java SE 8 and later, you can use the long data type to
represent an unsigned 64-bit long, which has a minimum value of 0 and a
maximum value of 264-1. The Long class also contains methods like
comparing Unsigned, divide Unsigned, etc to support arithmetic operations
for unsigned long.
Type 6: float
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a
float (instead of double) if you need to save memory in large arrays of
floating-point numbers.
Syntax:
float floatVar;
Size: 4 byte (32 bits)
Values: upto 7 decimal digits
Note: The default value is ‘0.0’.
Example:
• Java
// Java Program to Illustrate Float Primitive Data Type
import java.io.*;
// Class
class GFG {
// Print statement
// System.out.println(value1);
System.out.println(value2);
Output
9.87
If we uncomment lines no 14,15,16 then the output would have been totally
different as we would have faced an error.
Type 7: double
The double data type is a double-precision 64-bit IEEE 754 floating-point.
For decimal values, this data type is generally the default choice.
Syntax:
double doubleVar;
Size: 8 bytes or 64 bits
Values: Upto 16 decimal digits
Note:
• The default value is taken as ‘0.0’.
• Both float and double data types were designed especially for
scientific calculations, where approximation errors are acceptable. If
accuracy is the most prior concern then, it is recommended not to
use these data types and use BigDecimal class instead.
It is recommended to go through rounding off errors in java.
Type 8: char
The char data type is a single 16-bit Unicode character.
Syntax:
char charVar;
Size: 2 byte (16 bits)
Values: ‘\u0000’ (0) to ‘\uffff’ (65535)
Note: The default value is ‘\u0000’
You must be wondering why is the size of char 2 bytes in Java?
So, in other languages like C/C++ uses only ASCII characters, and to
represent all ASCII characters 8-bits is enough. But java uses the Unicode
system not the ASCII code system and to represent the Unicode system 8
bits is not enough to represent all characters so java uses 2 bytes for
characters. Unicode defines a fully international character set that can
represent most of the world’s written languages. It is a unification of dozens
of character sets, such as Latin, Greeks, Cyrillic, Katakana, Arabic, and
many more.
Example:
• Java
// Java Program to Demonstrate Char Primitive Data Type
// Class
class GFG {
char a = 'G';
// Integer data type is generally
int i = 89;
// if memory is a constraint
byte b = 4;
// byte b1 = 7888888955;
short s = 56;
// short s1 = 87878787878;
// is double in java
double d = 4.355453532;
float f = 4.7333434f;
long l = 12121;
System.out.println("char: " + a);
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Loops in Java
• Difficulty Level : Easy
• Last Updated : 11 May, 2022
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 all the ways provide
similar basic functionality, they differ in their syntax and condition checking
time.
• while loop: A while loop is a control flow statement that allows code to
be executed repeatedly based on a given Boolean condition. The while
loop can be thought of as a repeating if statement.
Syntax :
Example:
• Java
// Java program to illustrate If statement
class IfDemo {
int i = 10;
if (i > 15)
Output
I am Not in if
2. if-else: The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it won’t. But what if
we want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:
• Java
// Java program to illustrate if-else statement
class IfElseDemo {
int i = 10;
if (i < 15)
else
Output
i is smaller than 15
3. nested-if: A nested if is an if statement that is the target of another if or
else. 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 (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example:
• Java
// Java program to illustrate nested-if statement
class NestedIfDemo {
int i = 10;
if (i == 10 || i<15) {
// First if statement
if (i < 15)
// Nested - if statement
// it is true
if (i < 12)
System.out.println(
} else{
Output
i is smaller than 15
i is smaller than 12 too
Example:
• Java
// Java program to illustrate if-else-if ladder
class ifelseifDemo {
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
Output
i is 20
Example:
• Java
// Java program to illustrate using
// continue in an if statement
class ContinueDemo {
if (i % 2 == 0)
continue;
Output
1 3 5 7 9