java notes
java notes
In this section, we will learn how to write the simple program of Java. We can write a simple hello world
Java program easily after installing the JDK.
For creating a program it is necessary to create a class that contains the main() method (entry point of the
program). Before moving forward in this section, let's understand the requirement first.
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Parameters used in First Java Program
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it does not require creating an object to
invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it does not return any value.
o The main() method represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in coming
section.
o System.out.println() is used to print statement on the console. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class. We will discuss the
internal working of System.out.println() statement in the coming section.
Let's see the different codes to write the main method.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
Variables
A variable is a container which holds the value while the program is executed. A variable is assigned
with a data type.
Variable is a name of memory location. There are three types of variables: local, instance and static.
There are two types of data types:
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:
o local variable
o instance variable
o static variable
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.
Example to understand the types of variables
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
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);
}
}
Data Types
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.
Primitive data types:
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
Boolean Data Type
In Java, the boolean data type represents a single bit of information with two possible
states: true or false. It is used to store the result of logical expressions or conditions. Unlike other
primitive data types like int or double, boolean does not have a specific size or range. It is typically
implemented as a single bit, although the exact implementation may vary across platforms.
Example:
1. Boolean a = false;
2. Boolean b = true;
One key feature of the boolean data type is its use in controlling program flow. It is commonly employed
in conditional statements such as if, while, and for loops to determine the execution path based on the
evaluation of a boolean expression. For instance, an if statement executes a block of code if the boolean
expression evaluates to true, and skips it if the expression is false.
Byte Data Type
The byte data type in Java is a primitive data type that represents an 8-bit signed two's complement
integer. It has a range of values from -128 to 127. Its default value is 0. The byte data type is commonly
used when working with raw binary data or when memory conservation is a concern, as it occupies less
memory than larger integer types like int or long.
Example:
byte a = 10, byte b = -20
One common use of the byte data type is in reading and writing binary data, such as files or network
streams. Since binary data is often represented using bytes, the byte data type provides a convenient way
to work with such data. Additionally, the byte data type is sometimes used in performance-critical
applications where memory usage needs to be minimized.
Short Data Type
The short data type in Java is a primitive data type that represents a 16-bit signed two's complement
integer. It has a range of values from -32,768 to 32,767. Similar to the byte data type, short is used when
memory conservation is a concern, but more precision than byte is required. Its default value is 0.
Example:
short s = 10000, short r = -5000
In Java, short variables are declared using the short keyword. For example, short myShort =
1000; declares a short variable named myShort and initializes it with the value 1000. As with
the byte data type, short variables must be explicitly cast when used in expressions with larger integer
types to avoid loss of precision.
Int Data Type
The int data type in Java is a primitive data type that represents a 32-bit signed two's complement integer.
It has a range of values from -2,147,483,648 to 2,147,483,647. The int data type is one of the most
commonly used data types in Java and is typically used to store whole numbers without decimal points.
Its default value is 0.
Example:
int a = 100000, int b = -200000
In Java, int variables are declared using the int keyword. For example, int myInt = 100; declares an int
variable named myInt and initializes it with the value 100. int variables can be used in mathematical
expressions, assigned to other int variables, and used in conditional statements.
Long Data Type
The long data type in Java is a primitive data type that represents a 64-bit signed two's complement
integer. It has a wider range of values than int, ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. Its default value is 0.0F. The long data type is used when int is not large
enough to hold the desired value, or when a larger range of integer values is needed.
Example:
long a = 100000L, long b = -200000L
The long data type is commonly used in applications where large integer values are required, such as in
scientific computations, financial applications, and systems programming. It provides greater precision
and a larger range than int, making it suitable for scenarios where int is insufficient.
Float Data Type
The float data type in Java is a primitive data type that represents single-precision 32-bit IEEE 754
floating-point numbers. It can represent a wide range of decimal values, but it is not suitable for precise
values such as currency. The float data type is useful for applications where a higher range of values is
needed, and precision is not critical.
Example:
float f1 = 234.5f
One of the key characteristics of the float data type is its ability to represent a wide range of values, both
positive and negative, including very small and very large values. However, due to its limited precision
(approximately 6-7 significant decimal digits), it is not suitable for applications where exact decimal
values are required.
Double Data Type
The double data type in Java is a primitive data type that represents double-precision 64-bit IEEE 754
floating-point numbers. Its default value is 0.0d. It provides a wider range of values and greater precision
compared to the float data type, making it suitable for applications where accurate representation of
decimal values is required.
Example:
double d1 = 12.3
One of the key advantages of the double data type is its ability to represent a wider range of values with
greater precision compared to float. It can accurately represent values with up to approximately 15-16
significant decimal digits, making it suitable for applications that require high precision, such as financial
calculations, scientific computations, and graphics programming.
Char Data Type
The char data type in Java is a primitive data type that represents a single 16-bit Unicode character. It can
store any character from the Unicode character set, that allows Java to support internationalization and
representation of characters from various languages and writing systems.
Example:
char letterA = 'A'
The char data type is commonly used to represent characters, such as letters, digits, and symbols, in Java
programs. It can also be used to perform arithmetic operations, as the Unicode values of characters can be
treated as integers. For example, you can perform addition or subtraction operations on char variables to
manipulate their Unicode values.
Non-Primitive Data Types
In Java, non-primitive data types, also known as reference data types, are used to store complex objects
rather than simple values. Unlike primitive data types that store the actual values, reference data types
store references or memory addresses that point to the location of the object in memory. This distinction
is important because it affects how these data types are stored, passed, and manipulated in Java programs.
Class
One common non-primitive data type in Java is the class. Classes are used to create objects, which are
instances of the class. A class defines the properties and behaviors of objects, including variables (fields)
and methods. For example, you might create a Person class to represent a person, with variables for the
person's name, age, and address, and methods to set and get these values.
Interface
Interfaces are another important non-primitive data type in Java. An interface defines a contract for what
a class implementing the interface must provide, without specifying how it should be implemented.
Interfaces are used to achieve abstraction and multiple inheritance in Java, allowing classes to be more
flexible and reusable.
Arrays
Arrays are a fundamental non-primitive data type in Java that allow you to store multiple values of the
same type in a single variable. Arrays have a fixed size, which is specified when the array is created, and
can be accessed using an index. Arrays are commonly used to store lists of values or to represent matrices
and other multi-dimensional data structures.
Enum
Java also includes other non-primitive data types, such as enums and collections. Enums are used to
define a set of named constants, providing a way to represent a fixed set of values. Collections are a
framework of classes and interfaces that provide dynamic data structures such as lists, sets, and maps,
which can grow or shrink in size as needed.
Overall, non-primitive data types in Java are essential for creating complex and flexible programs. They
allow you to create and manipulate objects, define relationships between objects, and represent complex
data structures. By understanding how to use non-primitive data types effectively, you can write more
efficient and maintainable Java code.
Operators in Java
Operator is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Unary Operator
The unary operators require only one operand. Unary operators are used to perform various operations
i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Unary Operator Example: ++ and --
public class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Unary Operator Example: ~ and !
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
Arithmetic Operators
Arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.
Arithmetic Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Left Shift Operator
The left shift operator << is used to shift all of the bits in a value to the left side of a specified number of
times.
Left Shift Operator Example
public class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
Right Shift Operator
The right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.
Right Shift Operator Example
public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}
Ternary Operator
Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Ternary Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Assignment Operator
Assignment operator is one of the most common operators. It is used to assign the value on its right to the
operand on its left.
Assignment Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
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. It 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.
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.
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.
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.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Single-Dimensional Array in Java
A single-dimensional array in Java is a linear collection of elements of the same data type. It is declared
and instantiated using the following syntax:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Declaration, Instantiation and Initialization of Array
You can declare, instantiate, and initialize an array in a single line, as demonstrated below:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
For-each Loop for Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one
by one. It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array)
{
//body of the loop
}
Testarray1.java
//Java Program to print the array elements using for-each loop
class Testarray1
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Passing Array to a Method in Java
We can pass the Java array to the method so that we can reuse the same logic on any array. When we pass
an array to a method in Java, we are essentially passing a reference to the array. It means that the method
will have access to the same array data as the calling code, and any modifications made to the array
within the method will affect the original array.
Testarray2.java
//Java Program to demonstrate the way of passing an array
//to method.
class Testarray2
{
//creating a method which receives an array as a parameter
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Returning Array from the Method
In Java, methods are not limited to returning simple data types or objects; they can also return arrays. This
feature allows for more flexibility in method design and enables developers to encapsulate complex logic
for generating arrays within methods.
TestReturnArray.java
//Java Program to return an array from the method
class TestReturnArray
{
//creating method which returns an array
static int[] get()
{
return new int[]{10,30,50,90,60};
}
public static void main(String args[])
{
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Multidimensional Array in Java
A multidimensional array in Java is an array of arrays where each element can be an array itself. It is
useful for storing data in row and column format.
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
TestMultiArray.java
class TestMultiArray
{
public static void main(String args[])
{
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Addition of Two Matrices in Java
A fundamental operation in linear algebra and computer science, matrix addition is frequently utilised in a
variety of applications, including scientific computing, computer graphics, and image processing. To
create a new matrix with the same dimensions as the original, matching elements from each matrix must
be added when adding two matrices in Java. This Java program shows how to add matrices effectively by
using stacked loops to do a basic example of the process.
ArrayAddition.java
//Java Program to demonstrate the addition of two matrices in Java
class ArrayAddition
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}