Unit 2
Unit 2
JAVA UNIT -2
In Java, every line of code that can actually run needs to be inside a class. This line
declares a class named Main, which is public, that means that any other class can
access it. For now, we'll just write our code in a class called Main. Its either Public or
nothing.
Notice that when we declare a public class, we must declare it inside a file with the
same name (Main.java), otherwise we'll get an error when compiling.
This is the entry point of our Java program. the main method has to have this exact
signature in order to be able to run our program.
The arguments we get inside the method are the arguments that we will get when
running the program with parameters. It's an array of strings.
● System is a pre-defined class that Java provides us and it holds some useful
methods and variables.
● out is a static variable within System that represents the output of your program
(stdout).or it is a reference variable pointing to a object i.e out. ( :. Reference
variables are used to refer to an object. They are declared with a specific type that
cannot be changed.)
● println is a method of out that can be used to print a line.
● Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.
● Class − A class can be defined as a template/blueprint that describes the
It is in methods where the logics are written, data is manipulated and all the
● Instance Variables − Each object has its unique set of instance variables. An
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are called
identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
● All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
● After the first character, identifiers can have any combination of characters.
● A key word cannot be used as an identifier.
● Most importantly, identifiers are case sensitive.
● Examples of legal identifiers: age, $salary, _value, __1_value.
● Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two
categories of modifiers −
Java Variables
Following are the types of variables in Java −
● Local Variables
● Class Variables (Static Variables)
● Instance Variables (Non-static Variables)
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 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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Literals in Java
Literal : Any constant value which can be assigned to the variable is called as literal/constant.
int x = 100;
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
The table below shows the primitive type and the equivalent wrapper class:
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
We have classes for all data types and we call them as wrapper classes.
Eg. int data = 20;
( this data is called as variable, not objects)
To make it as object,
Use of instanceof
Output:true
int a = 5;
double b = 5.65;
Output
In the above example, we have used the valueOf() method to convert the primitive types
into objects. Here, we have used the instanceof operator to check whether the generated
objects are of Integer or Double type or not. However, the Java compiler can directly
convert the primitive types into corresponding objects. For example,
int a = 5;
// converts into object
Integer aObj = a;
double b = 5.6;
// converts into object
Double bObj = b;
Program;
public class Main {
int a = 5;
// converts into object
Integer aObj = a;
double b = 5.6;
// converts into object
Double bObj = b;
int a = aObj.intValue();
double b = bObj.doubleValue();
Output
The value of a: 23
In the above example, we have used the intValue() and doubleValue() method to convert
the Integer and Double objects into corresponding primitive types.
However, the Java compiler can automatically convert objects into corresponding primitive
types. For example,
int a = aObj;
double b = bObj;
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
● Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Disadvantages
● Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
1. arrayRefVar=new datatype[size];
Test it Now
Output:
10
20
70
40
50
10.
11.
Output:
33
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
Output:
33
18. }
19. }
Let's see the simple example to get the minimum number of an array using a method.
10.
11. System.out.println(min);
12. }
13.
Output:
9.
Output:
10
22
44
66
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.
Output:
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Output:
123
245
445
1. Manual Copy
public class Main
{
public static void main(String[] args)
{
System.out.println("\nContents of copyArray[]:");
for (int i=0; i<copyArray.length; i++)
System.out.print(copyArray[i] + " ");
}
}
Output:
Test it Now
Output:
caffein
8.
13.
14. }}
Output:
33
33
13.
14. System.out.println();
15. System.out.println("Array b is: ");
16. for(int i=0;i<2;i++){
17. for(int j=0;j<3;j++){
18. System.out.print(b[i][j]+" ");
19. }
20. System.out.println();//new line
21. }
22. System.out.println();
23. //creating another matrix to store the sum of two matrices
24. int c[][]=new int[2][3];
25.
35.
36. }}
37.
Output:
Array a is:
134
345
Array b is:
134
345
268
6 8 10
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
7.
10.
Test it Now
Output:
666
12 12 12
18 18 18
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
● Unary Operator,
● Arithmetic Operator,
● Shift Operator,
● Relational Operator,
● Bitwise Operator,
● Logical Operator,
● Assignment Operator.
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Output:
10
12
12
10
7.
8. }}
Output:
22
21
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}
Output:
15
50
Output:
21
The bitwise & operator always checks both conditions whether first condition is true or false.
Output:
Another Example:
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
Output:
14
16
Output:
13
18
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words which acts as a key
to a code. These are predefined words by Java so it cannot be used as a variable or object name.
1. abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide the
implementation of 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 loop or switch statement. It breaks the current flow of
the program at specified condition.
4. byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
5. case: Java case keyword is used to 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
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 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 a 64-bit floating-point
numbers.
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 applied
with a variable. It is used to restrict the user.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always
executed whether 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 conditions become 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 condition is true.
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).
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 package and
outside the package but through inheritance only. It can't be applied on 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 used for memory management mainly.
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 parent class object. It can
be used to invoke 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 exception. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exception 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 while loop.
Control statements
● if statement
● if-else statement
● if-else-if ladder
● nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
1. if(condition){
2. //code to be executed
3. }
Example:
Test it Now
Output:
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
Example:
13. }
14. }
Output:
odd number
Output:
LEAP YEAR
Example:
Output:
odd number
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Example:
7. if(marks<50){
8. System.out.println("fail");
9. }
10. else if(marks>=50 && marks<60){
11. System.out.println("D grade");
12. }
13. else if(marks>=60 && marks<70){
Output:
C grade
Output:
NEGATIVE
Syntax:
1. if(condition){
2. //code to be executed
3. if(condition){
4. //code to be executed
5. }
6. }
Example:
Test it Now
Output:
Example 2:
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
1. jump-statement;
2. break;
Output:
The Java continue statement is used to continue the loop. It continues the current flow of the program
and skips the remaining code at the specified condition. In case of an inner loop, it continues the inner
loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
1. jump-statement;
2. continue;
Test it Now
Output:
10
As you can see in the above output, 5 is not printed on the console. It is because the loop is continued
when it reaches to 5.
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly when
some conditions become true. There are three types of loops in Java.
● for loop
● while loop
● do-while loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed,
it is recommended to use for loop.
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop.
It continues execution until the condition is false. It must return boolean value either true or false.
It is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
1. for(initialization;condition;incr/decr){
2. //statement or code to be executed
3. }
Flowchart:
Example:
Test it Now
Output:
10
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
1. for(Type var:array){
2. //code to be executed
3. }
Example:
6. int arr[]={12,23,44,56,78};
7. //Printing array using for-each loop
8. for(int i:arr){
9. System.out.println(i);
10. }
11. }
12. }
Test it Now
Output:
12
23
44
56
78
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
1. labelname:
2. for(initialization;condition;incr/decr){
3. //code to be executed
4. }
Example:
9. if(i==2&&j==2){
10. break aa;
11. }
12. System.out.println(i+" "+j);
13. }
14. }
15. }
16. }
Output:
1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behavior of any loop.
Output:
1 1
1 2
1 3
2 1
3 1
3 2
33
Syntax:
1. for(;;){
2. //code to be executed
3. }
Example:
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
Ctrl+c
Syntax:
1. while(condition){
2. //code to be executed
3. }
Example:
Test it Now
Output:
1
2
3
4
5
6
7
8
9
10
Syntax:
1. while(true){
2. //code to be executed
3. }
Example:
Output:
ctrl+c
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
1. do{
2. //code to be executed
3. }while(condition);
Example:
Test it Now
Output:
1
2
3
4
5
6
7
8
9
10
Syntax:
1. do{
2. //code to be executed
3. }while(true);
Example:
Output:
ctrl+c
Switch:
}
Output:
Thursday
For Strings:
Vowel Checking:
char ch = 'z';
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println(ch + " is vowel");
break;
default:
System.out.println(ch + " is consonant");
}
}
}
Or
import java.util.Scanner;
public class VowelSwitch {
public static void main(String args[]) {
boolean bool = false;
System.out.println("Enter a character :");
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
switch(ch) {
case 'A':
case 'E' :
case 'I' :
case 'O' :
case 'U' :
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' : System.out.println("Given character is an vowel ");
break;
default:
System.out.println("Given character is a consonant");
}
}
}
Classes and Objects
Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car,
etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the
banking system.
● Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
● Identity: An object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write,
so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are created.
So, an object is the instance(result) of a class.
Object Definitions:
● Fields
● Methods
● Constructors
● Blocks
1. class <class_name>{
2. field;
3. method;
4. }
Create a Class
To create a class, use the keyword class:
int x = 5;
Create an Object
In Java, an object is created from a class. We have already created the class named
MyClass, so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name, and
use the keyword new:
int x = 5;
System.out.println(myObj.x);
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
● Code Reusability
● Code Optimization
File: Student.java
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }
Test it Now
Output:
0
null
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a
single Java source file, it is a good idea to save the file name with the class name which has main()
method.
File: TestStudent1.java
13. System.out.println(s1.name);
14. }
15. }
Test it Now
Output:
0
null
1. By reference variable
2. By method
3. By constructor
File: TestStudent2.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12. }
Test it Now
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);
17. System.out.println(s2.id+" "+s2.name);
18. }
19. }
Test it Now
Output:
101 Sonoo
102 Amit
File: TestStudent4.java
1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19. }
Test it Now
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area. The reference variable
refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that
refer to the objects allocated in memory.
File: TestEmployee.java
1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23. }
24. }
Test it Now
Output:
File: TestRectangle1.java
1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. }
10. class TestRectangle1{
11. public static void main(String args[]){
Test it Now
Output:
55
45
● By new keyword
● By newInstance() method
● By clone() method
● By deserialization
Anonymous object
Anonymous simply means nameless. An object which has no reference is known as an anonymous object.
It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach. For example:
1. new Calculation().fact(5);
1. class Calculation{
2. void fact(int n){
3. int fact=1;
4. for(int i=1;i<=n;i++){
5. fact=fact*i;
6. }
7. System.out.println("factorial is "+fact);
8. }
9. public static void main(String args[]){
10. new Calculation().fact(5);//calling method with anonymous object
11. }
12. }
Output:
Factorial is 120
Test it Now
Output:
55
45
38. a1.display();
39. a1.checkBalance();
40. a1.deposit(40000);
41. a1.checkBalance();
42. a1.withdraw(15000);
43. a1.checkBalance();
44. }}
Test it Now
Output:
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class
is created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor if
int l,b,h;
public Box()
// Outputs 5
Note that the constructor name must match the class name, and it cannot have a
return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
2. Parameterized constructor
1. <class_name>(){}
1. class Bike1{
2. //creating a default constructor
3. Bike1()
4. {System.out.println("Bike is created");
5. }
6. //main method
7. public static void main(String args[]){
8. //calling a default constructor
9. Bike1 b=new Bike1();
10.}
11.}
Output:
Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
2. Constructor Parameters
Example 1.
Ex-2:
int x;
public MyClass(int y) {
x = y;
System.out.println(myObj.x);
}// Outputs 5
Example 2:
int modelYear;
String modelName;
modelYear = year;
modelName = name;
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
3. Block
4. Nested class
● The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
● The static variable gets memory only once in the class area at the time of class loading.
1. class Student{
2. int rollno; // instance variable
3. String name;
4. String college="NIEC";
5. }
Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.
22. s2.display();
23. }
24.}
Output:
2. //which get memory each time when we create an object of the class.
3. class Counter{
4. int count=0;//will get memory each time when the instance is created
5. Counter(){
6. count++;//incrementing value
7. System.out.println(count);
8. }
9.
Output:
Output:
● A static method belongs to the class rather than the object of a class.
● A static method can be invoked without the need for creating an instance of a class.
● A static method can access static data member and can change the value of it.
class MathOperation
{
static float mul(float x, float y)
{
return x*y;
}
System.out.println("b= "+b);
}
}
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31.}
Test it Now
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
Output:125
1. The static method can not use non static data member or call non-static method directly.
1. class A{
2. int a=40;//non static
3.
5.
6. }
7. public static void main(String args[]){
8. System.out.println("Hello main");
9. }
10.}
11.
12.
Hello main
public Test()
{
System.out.println("Constructor: x ="+x);
Output:
initialization block: x= 0
Constructor: x =5
initialization block: x= 0
Constructor: x =5
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it
is not possible to execute a Java class without the main method.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Output:
variable , method or data member. There are four types of access modifiers available in java:
1. Default: When no access modifier is specified for a class , method or data member – It is
said to be having the default access modifier by default.
○ The data members, class or methods which are not declared using any access modifiers i.e.
having default access modifier are accessible only within the same package.
2. In this example, we will create two packages and the classes in the packages will be
having the default access modifiers and we will try to access a class from one package
from a class of second package.
package p1;
class Example
void display()
System.out.println("Hello World!");
//default modifier
package p2;
import p1.*;
class ExampleNew
obj.display();
3. Private: The private access modifier is specified using the keyword private.
○ The methods or data members declared as private are accessible only within the class in
which they are declared.
○ Any other class of same package will not be able to access these members.
○ Top level Classes or interface can not be declared as private because
1. private means “only visible within the enclosing class”.
2. protected means “only visible within the enclosing class and any subclasses”
○ Hence these modifiers in terms of application to classes, they apply only to nested classes
and not on top level classes
In this example, we will create two classes A and B within same package p1. We will declare a
method in class A as private and try to access this method from class B and see the result.
//Java program to illustrate error while using class from different package
with
//private modifier
package p1;
class A
System.out.println("GeeksforGeeks");
class B
obj.display();
Output:
error: display() has private access in A
obj.display();
4.
5. protected: The protected access modifier is specified using the keyword protected.
○ The methods or data members declared as protected are accessible within same package or
sub classes in different package.
6. In this example, we will create two packages p1 and p2. Class A in p1 is made public, to
access it in p2. The method display in class A is protected and class B is inherited from
class A and this protected method is then accessed by creating an object of class B.
//protected modifier
package p1;
//Class A
public class A
System.out.println("GeeksforGeeks");
//protected modifier
package p2;
//Class B is subclass of A
class B extends A
obj.display();
Output:
GeeksforGeeks
7. public: The public access modifier is specified using the keyword public.
○ The public access modifier has the widest scope among all other access modifiers.
○ Classes, methods or data members which are declared as public are accessible from every
where in the program. There is no restriction on the scope of a public data members
package p1;
public class A
System.out.println("GeeksforGeeks");
package p2;
import p1.*;
class B
A obj = new A;
obj.display();
Output:
GeeksforGeeks
8. Important Points:
○ If other programmers use your class, try to use the most restrictive access level that makes
sense for a particular member. Use private unless you have a good reason not to.
○ Avoid public fields except for constants.
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of our
examples:
The public keyword is an access modifier, meaning that it is used to set the access level for
classes, attributes, methods and constructors.
Access Modifiers
For classes, you can use either public or default:
Modifier Description
For attributes, methods and constructors, you can use the one of the following:
Modifier Description
default The code is only accessible in the same package. This is used
when you don't specify a modifier.
Non-Access Modifiers
For classes, you can use either final or abstract:
Modifier Description
abstract The class cannot be used to create objects (To access an abstract
class, it must be inherited from another class.
For attributes and methods, you can use the one of the following:
Modifier Description
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on
methods. The method does not have a body, for example abstract
void run();. The body is provided by the subclass (inherited from).
Final
If you don't want the ability to override existing attribute values, declare attributes as
final:
Example
Static
A static method means that it can be accessed without creating an object of the class,
unlike public:
Example
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Or
class MyClass {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
}
// Main method
public static void main(String[ ] args) {
MyClass.myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Abstract
The abstract keyword is a non-access modifier, used for classes and methods.
Class: An abstract class is a restricted class that cannot be used to create objects (to access
it, it must be inherited from another class).
Method: An abstract method can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).
An abstract method belongs to an abstract class, and it does not have a body. The body
is provided by the subclass.
Abstract class in Java is similar to interface except that it can contain default method
implementation. An abstract class can have an abstract method without body and it can have
methods with implementation also.
abstract keyword is used to create a abstract class and method. Abstract class in java can’t be
instantiated. An abstract class is mostly used to provide a base for subclasses to extend and
implement the abstract methods and override or use the implemented methods in abstract class
If one class is existing within another class is known as inner class or nested class. Inner classes are a security
mechanism in Java. We know a class cannot be associated with the access modifier private, but if
we have the class as a member of other class, then the inner class can be made private. And this
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class,
an inner class can be private and once you declare an inner class private, it cannot be accessed
Syntax
class Outerclass_name
{
.....
.....
class Innerclass_name1
{
.....
.....
}
class Innerclass_name1
{
.....
.....
}
.....
}
Private is a keyword in java language, it is preceded by any variable that property can be access only within the
Any non-static nested class is known as inner class in java. Java inner class is associated with the object
of the class and they can access all the variables and methods of the outer class. Since inner classes are
associated with the instance, we can’t have any static variables in them.
The object of java inner class are part of the outer class object and to create an instance of the inner
class, we first need to create an instance of outer class.
In Java, it is also possible to nest classes (a class within a class). The purpose of nested
classes is to group classes that belong together, which makes your code more readable and
maintainable.
To access the inner class, create an object of the outer class, and then create an object of
the inner class:
Example
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
System.out.println(myInner.y + myOuter.x);
// Outputs 15 (5 + 10)
EXAMPLE 2:
class Outer
class Inner{
int in=10;
void infunc()
}}
o1.infunc();
Output:
in= 10
class Outer
class Inner{
void infunc()
}}
o1.infunc();
An inner class can also be static, which means that you can access it without creating an
object of the outer class:
Example
class OuterClass {
int x = 10;
int y = 5;
System.out.println(myInner.y);
// Outputs 5
Note: just like static attributes and methods, a static inner class does not have access to
members of the outer class.
Example
class OuterClass {
int x = 10;
int y = 5;
System.out.println(myInner.y + myOuter.x);
If you try to access a private inner class from an outside class (MyMainClass), an error occurs:
class Outer_Demo {
int num;
// inner class
void display_Inner() {
inner.print();
outer.display_Inner();
Example
class OuterClass {
int x = 10;
class InnerClass {
return x;
System.out.println(myInner.myInnerMethod());
// Outputs 10
A nested class that doesn't have any name is known as an anonymous class.
An anonymous class must be defined inside another class. Hence, it is also known as an
anonymous inner class. Its syntax is:
class outerClass {
Note: Anonymous classes are defined inside an expression. So, the semicolon is used at
the end of anonymous classes to indicate the end of the expression.
2 Important points:
Reference variable is ob, of type A. So, ob can only access the functions from
class A. ob.f3() will give error coz if there is reference variable of parent (A)
and it is referring object of child (ie B). So, they can't call the methods of
original methods made in child class. (Concept of Early Binding)
When we override the version of parent class. Always, there is late binding occurs for
overridden functions. So, in this case, it will not make basis for reference type (A), but
instead what that type is pointing to.
class A
System.out.println("A show()");
A obj=new A();
obj.show();
class A
System.out.println("A show()");
class B extends A
System.out.println("B show()");
A obj=new B();
obj.show();
class A
System.out.println("A show()");
A obj=new A(){
System.out.println("B show()");
};
obj.show();
class Greeting
{
public void sayHello()
{
System.out.println("hello");
}
}
}
}
Output:
Namasty
class Vehicle
{
void start() {
System.out.println("Vehicle Started");
}
@Override
void start() {
System.out.println("Car Started");
}
vehicle.start();
vehicle.stop();
}
}
Output:
Car Started
Vehicle Stopped
Static method cannot be overridden. Ie y stop function of parent class is called (Early
binding). But, in non static method, it has overridden and child class of start function is
called.(Late Binding)
Java Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends). The
body of the interface method is provided by the "implement" class:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
Notes on Interfaces:
● Like abstract classes, interfaces cannot be used to create objects (in the example above,
it is not possible to create an "Animal" object in the MyMainClass)
● Interface methods do not have a body - the body is provided by the "implement" class
● On implementation of an interface, you must override all of its methods
● Interface methods are by default abstract and public
● Interface attributes are by default public, static and final
● An interface cannot contain a constructor (as it cannot be used to create objects)
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma (see example below).
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
1. Type of methods: Interface can have only abstract methods. Abstract class can have
abstract and non-abstract methods. From Java 8, it can have default and static methods
also.
2. Final Variables: Variables declared in a Java interface are by default final. An abstract
class may contain non-final variables.
3. Type of variables: Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.
4. Implementation: Abstract class can provide the implementation of interface. Interface
can’t provide the implementation of abstract class.
5. Inheritance vs Abstraction: A Java interface can be implemented using keyword
“implements” and abstract class can be extended using keyword “extends”.
6. Multiple implementation: An interface can extend another Java interface only, an abstract
class can extend another Java class and implement multiple Java interfaces.
7. Accessibility of Data Members: Members of a Java interface are public by default. A
Java abstract class can have class members like private, protected, etc.
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
also.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
4) Abstract class can provide the Interface can't provide the implementation of
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract class can extend another Java An interface can extend another Java interface only.
7) An abstract class can be extended using An interface can be implemented using keyword
8) A Java abstract class can have class Members of a Java interface are public by default.
9)Example: Example:
Java ArrayList
The ArrayList class is a resizable array, which can be found in the java.util
package.ArrayList is a part of collection framework and is present in java.util package.
The difference between a built-in array and an ArrayList in Java, is that the size of an
array cannot be modified (if you want to add or remove elements to/from an array, you
have to create a new one). While elements can be added and removed from an ArrayList
whenever you want. The syntax is also slightly different:
Example: Create an ArrayList object called cars that will store strings:
import java.io.*;
import java.util.*;
Add Items
The ArrayList class has many useful methods. For example, to add elements to the
ArrayList, use the add() method:
Example
import java.util.ArrayList;
Access an Item
To access an element in the ArrayList, use the get() method and refer to the index
number:
Example
cars.get(0);
Remember: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Item
To modify an element, use the set() method and refer to the index number:
Example
cars.set(0, "Opel");
Remove an Item
To remove an element, use the remove() method and refer to the index number:
Example
cars.remove(0);
To remove all the elements in the ArrayList, use the clear() method:
Example
cars.clear();
ArrayList Size
To find out how many elements an ArrayList have, use the size method:
Example
cars.size();
Example
You can also loop through an ArrayList with the for-each loop:
Example
Other Types
Elements in an ArrayList are actually objects. In the examples above, we created elements
(objects) of type "String". Remember that a String in Java is an object (not a primitive
type). To use other types, such as int, you must specify an equivalent wrapper class:
Integer. For other primitive types, use: Boolean for boolean, Character for char, Double
for double, etc:
Example
import java.util.ArrayList;
Sort an ArrayList
Another useful class in the java.util package is the Collections class, which include the
sort() method for sorting lists alphabetically or numerically:
Example
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
Example
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of
the array automatically increases when we dynamically add and remove items. Though the actual
library implementation may be more complex, the following is a very basic idea explaining the
working of the array when the array becomes full and if we try to add an item:
● Creates a bigger sized memory on heap memory (for example memory of double size).
● Copies the current memory elements to the new memory.
● New item is added now as there is bigger memory available now.
● Delete the old memory.
Inheritance in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java
by which one class is allow to inherit the features(fields and methods) of another class.
Important terminology:
● Super Class: The class whose features are inherited is known as super class(or a base
class or a parent class).
● Sub Class: The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.
Syntax :
Example: In below example of inheritance, class Bicycle is a base class, class MountainBike is a
derived class which extends Bicycle class and class Test is a driver class to run program.
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
// derived class
class MountainBike extends Bicycle
{
// driver class
public class Test
{
public static void main(String args[])
{
}
}
Output:
No of gears are 3
seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all methods and
fields of the superclass acquire memory in this object. That is why, by using the object of the
Please note that during inheritance only object of subclass is created, not the superclass.
In practice, inheritance and polymorphism are used together in java to achieve fast performance and
readability of code.
INHERITANCE
by which one class is allowed to inherit the features(fields and methods) of another class.
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover,
you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Syntax:
The extends keyword indicates that you are making a new class that derives from an existing class. The
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is
Important terminology:
● Super Class: The class whose features are inherited is known as super class(or a base
class or a parent class).
● Sub Class: The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.
Simple Example:
● class Employee{
● float salary=40000;
● }
● class Programmer extends Employee{
● int bonus=10000;
● }
● }
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class
i.e. code reusability.
Access Modifiers
Access modifiers are simply a keyword in Java that provides accessibility of a class
and its member. They set the access level to methods, variable, classes and
constructors.
● public
● default
● protected
● private
public
The member with public modifiers can be accessed by any classes. The public
methods, variables or class have the widest scope.
// code
default
int a = 25;
boolean m1()
return true;
protected
The protected modifier is used within same package. It lies between public and default
access modifier. It can be accessed outside the package but through inheritance only.
class Employee
System.out.println("Employee Id : "+id);
pd.display();
Output:
Employee Id : 101
private
The private methods, variables and constructor are not accessible to any other class.
It is the most restrictive access modifier. A class except a nested class cannot be
private.
pd.show();
System.out.println(pd.a+" "+pd.s);
Output:
String s = TutorialRide
101 TutorialRide
private Yes No No No
}
}
public class InheritanceDemo
{
public static void main(String []args)
{
Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base class and as
well as the derived class also act as the base class to other class. In below image, the class A serves
as a base class for the derived class B, which in turn serves as a base class for the derived class C. In
{
public int sub(int a, int b)
{
return a-b;
}
}
Example
of Hierarchical Inheritance
class A
class B extends A
class C extends A
class D extends A
class JavaExample
obj1.methodA();
obj2.methodA();
obj3.methodA();
Output:
method of Class A
method of Class A
method of Class A
interface one
{
public void print_geek();
}
interface two
{
public void print_for();
}
// Drived class
c.print_geek();
c.print_for();
c.print_geek();
Output:
Geeks
for
Geeks
● Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.
● Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by
java.
● Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
● Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters and
setters) for accessing its private fields, these can also be used by the subclass.
In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new
members:
● The inherited fields can be used directly, just like any other fields.
● We can declare new fields in the subclass that are not in the superclass.
● The inherited methods can be used directly as they are.
● We can write a new instance method in the subclass that has the same signature as the
one in the superclass, thus overriding it (as in example above, toString() method is
overridden).
● We can write a new static method in the subclass that has the same signature as the one
in the superclass, thus hiding it.
● We can declare new methods in the subclass that are not in the superclass.
● We can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.
class Calc
{
int num1;
int num2;
int result;
Next Scenario:
class Calc
{
int num1;
int num2;
int result;
Output:
0
0
Use of this:
class Calc
{
int num1;
int num2;
int result;
}
}
Output:
4
5
The most common use of this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). If you omit the keyword in the example above, the
output would be "0" instead of "5".
The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
Ex-1
//WAP to demonstrate Super in inheritance
class Senior
{
int salary=4000;
}
Ex-2
//super can be used to invoke immediate parent class method
class Animal{
void eat()
{
System.out.println("Animal is eating...");}
}
class Dog extends Animal{
void eat()
{
System.out.println("Dog is eating bread...");
}
void bark()
{
System.out.println("Dog is barking...");
}
void work()
{
super.eat();
bark();
}
}
public class TestSuper2
{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
3. Super in Constructor
Case1:
class A
{
public A()
{
System.out.println("in A");
}
}
class B extends A
{
public B()
{
System.out.println("in B");
}
}
Output:
In A
Case 2:
class A
{
public A()
{
System.out.println("in A");
}
}
class B extends A
{
public B()
{
System.out.println("in B");
}
}
Output:
in A
in B
class A
{
public A()
{
System.out.println("in A");
}
public A(int i)
{
System.out.println("in A int");
}
}
class B extends A
{
//super();
public B()
{
System.out.println("in B");
}
public B(int i)
{
System.out.println("in B int");
}
}
Case 4:
class A
{
public A()
{
System.out.println("in A");
}
public A(int i)
{
System.out.println("in A int");
}
}
class B extends A
{
public B()
{
System.out.println("in B");
}
public B(int i)
{
super();
System.out.println("in B int");
}
}
Output:
in A
in B int
Case 5:
class A
{
public A()
{
System.out.println("in A");
}
public A(int i)
{
System.out.println("in A int");
}
}
class B extends A
{
public B()
{
System.out.println("in B");
}
public B(int i)
{
super(i);
System.out.println("in B int");
}
}
Output:
in A int
in B int
Case 6:
class A
{
public A()
{
System.out.println("in A");
}
public A(int i)
{
System.out.println("in A int");
}
}
class B extends A
{
public B()
{
//super();
System.out.println("in B");
}
public B(int i)
{
super(i);
System.out.println("in B int");
}
}
Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="java";
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and
StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a
new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool, that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
String str="Hello";
String str1="Java";
System.out.println(str.equals(str1));
String str2="HelloWorld";
String str3="HelloWorld";
System.out.println(str2.equals(str3));
Test it Now
java
strings
example
N Method Description
o.
index
4 static String format(Locale l, String format, Object... returns formatted string with given
args) locale.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index
CharSequence... elements)
given object.
13 String replace(char old, char new) replaces all occurrences of the specified
char value.
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.
check case.
17 String[] split(String regex, int limit) returns a split string matching regex
and limit.
20 int indexOf(int ch, int fromIndex) returns the specified char value index
22 int indexOf(String substring, int fromIndex) returns the specified substring index
specified locale.
specified locale.
of this string.
overloaded method.
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is
safe and will result in an order.
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
public append(String s) is used to append the specified string with this string. The
append(double) etc.
public insert(int offset, is used to insert the specified string with this string at the
public replace(int is used to replace the string from specified startIndex and
str)
public delete(int is used to delete the string from specified startIndex and
StringBuffer endIndex)
synchronized
StringBuffer
public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of
characters.
public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int is used to return the substring from the specified beginIndex
endIndex)
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder
classes are used for creating mutable string.
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Ex-2
sbf.append("Java");
System.out.println(sbf);
sbf.replace(0,4,"Hi");
System.out.println(sbf);
String s="Hello";
System.out.println(s);
s.concat("world");
System.out.println(s);
String s1=s.concat("Hi");
System.out.println(s1);
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
1. class StringBufferExample6{
import java.util.*;
Output:
Enter a String:
HelloWorld
Memory :
// String str="Hello";
// String str1="Java";
// System.out.println(str.equals(str1));
// String str2="HelloWorld";
// System.out.println(Integer.toHexString(str2.hashCode()));
// String str3="HelloWorld";
// System.out.println(Integer.toHexString(str3.hashCode()));
// str3=str3+"1";
// System.out.println(Integer.toHexString(str3.hashCode()));
// //System.out.println(str);//A
//System.out.println(str3); //B
//System.out.println(str3.equals(str4)); //C
//System.out.println(str2.equals(str3)); //D
System.out.println(Integer.toHexString(sb1.hashCode()));
System.out.println(sb);
System.out.println(Integer.toHexString(sb.hashCode()));
System.out.println(sb);
System.out.println(Integer.toHexString(sb.hashCode()));
N String StringBuffer
o.
2) String is slow and consumes more memory when you concat StringBuffer is fast and consumes
too many strings because every time it creates new instance. less memory when you cancat
strings.
3) String class overrides the equals() method of Object class. StringBuffer class doesn't override
So you can compare the contents of two strings by equals() the equals() method of Object
method. class.
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.
N StringBuffer StringBuilder
o.
safe. It means two threads can't call the thread safe. It means two threads can call
simultaneously.
StringBuilder. StringBuffer.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception handling. Let's
take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest
of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception
handling, the rest of the statement will be executed. That is why we use exception handling in Java.
Comparison Chart
BASIS FOR
ERROR EXCEPTION
COMPARISON
Keywords There is no means to Exceptions are handled using three keywords "try",
program code.
terminated abnormally.
package.
StackOverFlow.
Unchecked Exceptions : NullPointer,
IndexOutOfBounds.
3. Error
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions
are not checked at compile-time, but they are checked at runtime.
3) Error
An Error “indicates serious problems that a reasonable application should not try to catch.” Errors are
the conditions which cannot get recovered by any handling techniques. It surely cause termination of
the program abnormally. Errors belong to unchecked type and mostly occur at runtime. Some of the
examples of errors are Out of memory error or a System crash error. Error is irrecoverable e.g.
OutOfMemoryError, VirtualMachineError, AssertionError etc.
Keywo Description
rd
try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is always
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.
Output:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable
that has characters, converting this variable into digit will occur NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as
shown below:
If an exception occurs at the particular statement of try block, the rest of the block code will not execute.
So, it is recommended not to keeping the code in try block that will not throw an exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try
block.
Example 1
1. public class TryCatchExample1 {
2.
11. }
Output:
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Example 2
1. public class TryCatchExample2 {
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Output:
java.lang.ArithmeticException: / by zero
Now, as displayed in the above example, the rest of the code is executed, i.e., the rest of the code
statement is printed.
Example 3
In this example, we also kept the code in a try block that will not throw an exception.
16. }
17.
18. }
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.
Example 4
Here, we handle the exception using the parent class exception.
2.
Output:
java.lang.ArithmeticException: / by zero
Example 5
Let's see an example to print a custom message on exception.
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }
Output:
Example 6
Let's see an example to resolve the exception in a catch block.
Output:
25
Example 7
In this example, along with try block, we also enclose exception code in a catch block.
5. try
6. {
7. int data1=50/0; //may throw exception
8.
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // generating the exception in catch block
14. int data2=50/0; //may throw exception
15.
16. }
17. System.out.println("rest of the code");
18. }
19. }
Output:
Here, we can see that the catch block didn't contain the exception code. So, enclose exception code within
a try block and use catch block only to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a different type of
exception class (ArrayIndexOutOfBoundsException).
Output:
Example 9
Let's see an example to handle another unchecked exception.
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
Example 10
Let's see an example to handle checked exception.
1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }
Output:
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a
default exception handler that performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is maintained
i.e. rest of the code is executed.
N throw throws
o.
1) Java throw keyword is used to explicitly throw an Java throws keyword is used to declare an
exception. exception.
2) Checked exception cannot be propagated using Checked exception can be propagated with
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
IOException,SQLException.
else
{
int c;
c=a/b;
System.out.println("Result is " +c);
}
}
Case 2:
else
{
int c;
c=a/b;
System.out.println("Result is " +c);
}
}
Output:
Arithmetic Exception Caught
Concept of throws:
In case of checked Exceptions
import java.io.*;
public class Example
{
public static void main(String [] args)
{
throw new IOException();
System.out.println("Last statement");
}
}
Output:
Example.java:7: error: unreachable statement
System.out.println("Last statement");
^
Example.java:6: error: unreported exception IOException; must be caught or declared to be thrown
throw new IOException();
^
2 errors
Solution:
1. Either by try catch:
import java.io.*;
public class Example
{
public static void main(String [] args)
{
try{
throw new IOException();
}
catch(Exception e)
{
System.out.println("Caught");
}
System.out.println("Last statement");
}
}
2. Or by Throws
import java.io.*;
public class Example
{
public static void main(String [] args) throws IOException
{
Compile:
No Error
Output:
Exception in thread "main" java.lang.ArithmeticException
at Example.main(Example.java:6)
Throw keyword:
if(age<18)
else
obj.checkAge(13);
System.out.println("End Of Program");
Output:
at JavaTester.checkAge(JavaTester.java:4)
at JavaTester.main(JavaTester.java:10)
Throws:
int t = a/b;
return t;
try{
System.out.println(obj.division(15,0));
catch(ArithmeticException e){
Output:
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
import java.util.StringTokenizer;
while (st.hasMoreTokens()) {
System.out.println(st.countTokens());
System.out.println(st.nextToken());
OUtput:
5
This
4
is
3
StringTokenizer
2
-
1
-
There are some important differences between an applet and a standalone Java application, including
the following −
● init − This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
● start − This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
● stop − This method is automatically called when the user moves off the page on which the
● destroy − This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
● paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT. The AWT contains support for a window-based,
graphical user interface. java.applet.* imports the applet package, which contains the class
Applet. Every applet that you create must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed by code that
is outside the program.Every Applet application must declare a paint() method. This method is
defined by AWT class and must be overridden by the applet. The paint() method is called each
time when an applet needs to redisplay its output. Another important thing to notice about
applet application is that, execution of an applet does not begin at main() method. In fact an
applet application does not have any main() method.
Advantages of Applets
1. It takes very less response time as it works on the client side.
//java.applet.Applet
//java.awt.Graphics
import java.applet.*;
import java.awt.*;
These import statements bring the classes into the scope of our applet class −
● java.applet.Applet
● java.awt.Graphics
Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that
load and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
● init() : init() is the first method to be called. This is where variable are initialized. This
● start() : start() method is called after init(). This method is called to restart an applet
● stop() : stop() method is called to suspend thread that does not need to run when applet
is not visible.
● destroy() : destroy() method is called when your applet needs to be removed completely
from memory.