OOPJ
OOPJ
Introduction to OOP
Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism, etc. In programming. The main aim of OOP is
to bind together the data and the functions that operate on them so that no other
part of the code can access this data except that function.
Java Fundamentals
Keywords
Identifiers
Data Types
Variables
Literals
Operators
Data Types
Data types represent the type of data you want to use and memory required for that data.
There are two types of data:
These are predefined data types. There are eight types of primitive data types.
Primitive Default Range Default Example
Data Types Values Size
boolean False true/ false N/D boolean b = true
char 0 or 0 to 65535 (2^16-1) 2byte char c=’A’
\u0000 \u0000 to \uffff
byte 0 -128(-2^7) to 127 (2^7 -1) 1byte byte b = 12
short 0 -32,768 (-2^15) to 32,767(2^15 -1) 2byte short s=10
int 0 – 2,147,483,648 (-2^31) 2byte int I = 100
to2147483647(2^31 -1)
long 0 -2^63 to 2^63-1 8byte long l= 1000L
float 0.0 1.4E-45 to 3.40E+38 4byte float f = 25.9f
double 0.0 4.9E-324 to 1.79E+308 8byte double d =
152.3
Any Null Reference of the corresponding type 8byte String str=null
Reference object
type
These are the user-defined data types. There are four types of non-primitive data types:
Class type
Interface type
Enum type
Annotation type
Variables
Variable holds the user data. The memory will be allocated for the variables according to
the data type. Value of the variable can be changed any number of times during the program
execution. Syntax: <data type><var name>; or <data type><var name>=<value>;
Example: int a; int b=10; String s=”name”; String st; There are two types of variables based
on the data types used to declare the variable:
Primitive variables
Reference Variable
Primitive Variables
Variables declared with primitive data types are called as primitive variables. Example: int a,
char c, double b=10.0, etc.
Read our comprehensive guide to the Final Keyword in Java and become a Java master!
Reference Variable
Variables declared with used defined data types are called as reference variables.
Example:Stringstr; String s=”Intellipaat”;There are following types of variables based on the
scope of the variables:
Instance variables
Static variables
Local variables
Instance Variables
Variables declared without using static keyword inside of a class but outside of method is
called instance variables. Example: variable a in the above code. The Memory will be
allocated to the instance variable only at the time of object creation. As many times as the
object is created, the instance variable will get the memory.
Static Variables
Variables declared using static keyword inside of a class but outside of method are called
static variables. Example: variable b in the above code. The Memory will be allocated to
static variables at the time of object creation when the class loads. Static Variable will get the
memory only once when the class loads.
Local Variables
Variables declared inside of a method are called as Local variables. Example: variable c in
the above code.
Constants
Constants are the special variables whose value can’t be modified during the program
execution. These are also called final variables. Example:finalint a=99; final String
s=”Intellipaat”; final double d=10.1;
OPERATORS
Operators are the symbols that perform the operation on values. These values are known as
operands. There are three types of operators depending on the number of operands required:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operator
Arithmetic Operator
Relational Operator
Relational operators are used to check the relation between the two operands.
Result of the relational operator is always Boolean value.
&& Logical AND When Both conditions are true, the result
is true
otherwise false
|| Logical OR When at least one condition is true,
then the result is true otherwise false
! Logical NOT Reverse the condition
!true= false
!false= true
Assignment Operator
Bitwise Operators
<<= Left shift AND It performs Binary left shift and then result a=5; a>>=7 means
assignment is assigned to left-hand operand 7 times left shift,
operator then result to a
>>= Right shift AND It performs Binary right shift and then a=5; a>>=7 means
assignment result is assigned to left-hand operand 7 times right shift,
operator then result to a
&= Bitwise AND It performs bitwise AND then result is a=5; a&=7 means
assignment assigned to left-hand operand bitwise AND
operator operation, then
result to a
^= bitwise exclusive It performs bitwise exclusive OR and then a=5; a^=7 means
OR result is assigned to left-hand operand bitwise XOR
and assignment operation, then
operator result to a
<< Left shift operator It performs Binary left shift a<<1 means one
bit is left-shifted
>> Right It performs Binary right shift a>>1 means one
shiftoperator bit is right-shifted
& Bitwise AND It performs bitwise AND 5 & 7 means
binary XOR of 5
and 7
^ bitwise exclusive It performs bitwise exclusive OR 5^7 means binary
OR XOR operation on
5 and 7
| bitwise inclusive It performs bitwise inclusive OR 2|1 means 2 and 1
OR binary OR
operation
Conditional Operator
It is a ternary operator.
Here, t object will be created in the main memory so that we can access the members of
the Test class.
instanceof Operator
It is used to check whether the given object belongs to a specified class or not. It is also
called Type Comparision Operator. It returns a Boolean value.
Syntax: <reference variable>instanceof<classname>
Example:
Class Test{}
class IntellipaatLearn{
public static void main(String args[]){
Test t=new Tets(); // t object is createdSystem.out.println(t instanceof Object); // returns true
}
}
Output:
true
Operators Precedence
Operator precedence means the priorities of operators.
Say you have given an equation 10-2*2. How will you know whether to subtract first or
multiply? To solve this confusion, operator precedence has provided.
First, 2*2 will be performed according to the below table then, the result will be multiplied by
10. The answer will be 6.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ – – ! ~ Right to left
Multiplicative */% Left to right
Additive +– Left to right
Shift >>>>><< Left to right
Relational >>= <<= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>=<<= &= ^= |= Right to left
Comma , Left to right
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student named Ravi is
an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface
Class Declaration in Java
access_modifierclass <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
// Java program to Illustrate Creation of Object
// Main class
classGFG {
publicstaticvoidmain(String[] args)
try{
catch(ClassNotFoundException e) {
e.printStackTrace();
catch(InstantiationException e) {
e.printStackTrace();
catch(IllegalAccessException e) {
e.printStackTrace();
Java Methods
The method in Java or Methods of Java is a collection of statements that perform some
specific tasks and return the result to the caller. A Java method can perform some specific
tasks without returning anything. Java Methods allows us to reuse the code without
retyping the code. In Java, every method must be part of some class that is different from
languages like C, C++, and Python.
A method is like a function i.e. used to expose the behavior of an object.
It is a set of codes that perform a particular task.
Syntax of Method
<access_modifier><return_type><method_name>(list_of_parameters)
{
//body
}
Advantage of Method
Code Reusability
Code Optimization
Note: Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 types of access specifiers.
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its
subclasses.
private: It is accessible only within the class in which it is defined.
default: It is declared/defined without using any modifier. It is accessible
within the same class and package within which its class is defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value returned by the method or void if does not
return a value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as well, but the
convention is a little different. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded by
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can throw; you can specify
these exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations. It is Optional in syntax.
Types of Methods in Java
There are two types of methods in Java:
1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any
point.
2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Ways to Create Method in Java
There are some cases when we don’t know the number of parameters to be passed or an
unexpected case to use more parameters than declared number of parameters. In such cases
we can use
Passing Array as an Argument
Passing Variable-arguments as an Argument
Method Overloading.
Memory Allocation for Methods Calls
Methods calls are implemented through a stack. Whenever a method is called a stack frame
is created within the stack area and after that, the arguments passed to and the local
variables and value to be returned by this called method are stored in this stack frame and
when execution of the called method is finished, the allocated stack frame would be
deleted. There is a stack pointer register that tracks the top of the stack which is adjusted
accordingly.
// Define a class
publicclassExample{
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){this.name=name;}
Reusability: Methods allow you to write code once and use it many times, making your
code more modular and easier to maintain.
Abstraction: Methods allow you to abstract away complex logic and provide a simple
interface for others to use. This makes your code more readable and easier to
understand.
Improved readability: By breaking up your code into smaller, well-named methods,
you can make your code more readable and easier to understand.
Encapsulation: Methods allow you to encapsulate complex logic and data, making it
easier to manage and maintain.
Separation of concerns: By using methods, you can separate different parts of your
code and assign different responsibilities to different methods, improving the structure
and organization of your code.
Improved modularity: Methods allow you to break up your code into smaller, more
manageable units, improving the modularity of your code.
Improved testability: By breaking up your code into smaller, more manageable units,
you can make it easier to test and debug your code.
Improved performance: By organizing your code into well-structured methods, you
can improve performance by reducing the amount of code that needs to be executed and
by making it easier to cache and optimize your code.
Java compiler executes the code from top to bottom. The statements in the code are executed according to the
order in which they appear. However, Java provides statements that can be used to control the flow of Java code.
Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a
smooth flow of program.
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending upon
the result of the condition provided. There are two types of decision-making statements in Java, i.e., If
statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or
false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and
enables the program to enter a block of code if the expression evaluates to true.
if(condition)
{
statement 1; //executes when condition is true
}
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The
else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can
say that it is the chain of if-else statements that create a decision tree where the program may enter in the block
of code where the condition is true. We can also define an else statement at the end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of
code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Output:
While using switch statements, we must notice that the case expression will be of the same type as the variable.
However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to
true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of
the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and
condition checking time.
1. for loop
2. while loop
3. do-while loop
Output:
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we
don't need to update the loop variable. The syntax to use the for-each loop in java is given below.
Output:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if we don't know
the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
The do-while loop checks the condition at the end of the loop after executing the loop statements. When the
number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-
while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words, jump
statements transfer the execution control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program and transfer the
control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop
or switch statement.
BreakExample.java
Output:
0
1
2
3
4
5
6
Calculation.java
Output:
0
1
2
3
4
5
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the
loop and jumps to the next iteration of the loop immediately.
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
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++.
Output:
Java Constructors
Java constructors or constructors in Java is a terminology used to construct
something in our programs. A constructor in Java is a special method that is used to
initialize objects. The constructor is called when an object of a class is created. It can be
used to set initial values for object attributes.
What are 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 the constructor, memory for the object
is allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
Example of Java Constructor
importjava.io.*;
// Driver Class
classGeeks{
// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}
// main function
publicstaticvoidmain(String[]args)
{
Geeksgeek=newGeeks();
}
}
Output
Constructor Called
In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects. Due to this negligence, at
a certain point, sufficient memory may not be available to create new objects, and the entire
program will terminate abnormally, causing
UNIT 2
Java Strings
/ create a string
String type = "Java programming";
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
In the above example, we have created three strings named first , second ,
and third .
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
Output
In the above example, the length() method calculates the total number of
characters in the string and returns it.
2. Join Two Java Strings
We can join two strings in Java using the concat() method. For example,
classMain{
publicstaticvoidmain(String[] args){
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
Output
Here, the concat() method joins the second string to the first string and
assigns it to the joinedString variable.
We can also join two strings using the + operator in Java.
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
Output
and third .
Here, we are using the equal() method to check if one string is equal to
another.
The equals() method checks the content of strings while comparing them.
To learn more, visit Java String equals().
Escape Character in Java Strings
Here, we have created a string variable named example . The variable holds
the string "Hello! " .
Here, we are using the concat() method to add another string "World" to the
previous string.
It looks like we are able to change the value of the previous string.
However, this is not true .
In the above example, we have created a string name using the new keyword.
Here, when we create a string object, the String() constructor is invoked.
Example: Create Java Strings Using the New Keyword
classMain{
publicstaticvoidmain(String[] args){
Here, we are directly providing the value of the string ( Java ). Hence, the
compiler first checks the string pool to see if the string already exists.
If the string already exists, the new string is not created. Instead, the new
reference, example points to the already existing string ( Java ).
If the string doesn't exist, a new string ( Java) is created.
2. While creating strings using the new keyword,
replace() Replaces the specified old character with the specified new character.
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one
class (known as a subclass or derived class) to inherit properties and behaviors (methods)
from another class (known as a superclass or base class). This promotes code reusability and
helps in creating a hierarchical relationship between classes.
1. Single Inheritance: This is the simplest form of inheritance where a subclass inherits
from a single superclass. This helps in creating a straightforward hierarchy and
reusing code effectively.
o Example: If you have a class Animal and a subclass Dog that inherits from
Animal, Dog will inherit all the properties and methods of Animal.
2. Multiple Inheritance: In this type, a subclass can inherit from more than one
superclass. This allows a class to combine behaviors and attributes from multiple
classes. However, multiple inheritance can lead to complexities, such as the
"Diamond Problem" where ambiguity arises if two superclasses have a common
ancestor.
o Example: If you have classes Vehicle and Flyable, and a subclass
FlyingCar inherits from both, FlyingCar will get properties and methods
from both Vehicle and Flyable.
3. Multilevel Inheritance: In this type, a subclass inherits from another subclass,
forming a chain of inheritance. This means that the derived class at the end of the
chain inherits properties and methods from all the classes above it in the chain.
o Example: If Grandparent is inherited by Parent, and Parent is inherited by
Child, then Child will inherit properties and methods from both
Grandparent and Parent.
4. Hierarchical Inheritance: This occurs when multiple subclasses inherit from a single
superclass. This type of inheritance allows for a common base class with various
specialized derived classes.
o Example: If Animal is a superclass and Dog, Cat, and Bird are subclasses,
then all three subclasses inherit from Animal.
5. Hybrid Inheritance: This is a combination of two or more types of inheritance. It can
involve multiple, hierarchical, or other forms of inheritance. This type can sometimes
create complexities and ambiguity in the class hierarchy.
o Example: If a class A is the base class, B and C are derived from A, and D
inherits from both B and C, then D is an example of hybrid inheritance.
// Java program to illustrate the
// concept of inheritance
// base class
classBicycle{
// the Bicycle class has two fields
publicintgear;
publicintspeed;
publicvoidspeedUp(intincrement)
{
speed+=increment;
}
// derived class
classMountainBikeextendsBicycle{
// driver class
publicclassTest{
publicstaticvoidmain(Stringargs[])
{
MountainBikemb=newMountainBike(3,100,25);
System.out.println(mb.toString());
}
}
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4. //Creating child classes.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15. //Test class to create objects and call the methods
16. class Test2{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
}
25. Output:
26. SBI Rate of Interest: 8
27. ICICI Rate of Interest: 7
28. AXIS Rate of Interest: 9
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
UNIT 3
Java Exceptions
When executing Java code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw an exception (throw
an error).
catch(Exceptione){
publicclassMain{
publicstaticvoidmain(String[]args){
int[]myNumbers={1,2,3};
System.out.println(myNumbers[10]);// error!
}
The output will be something like this:
Finally
The finally statement lets you execute code, after try...catch, regardless
of the result:
Example
publicclassMain{
publicstaticvoidmain(String[]args){
try{
int[]myNumbers={1,2,3};
System.out.println(myNumbers[10]);
}catch(Exception e){
}finally{
Try it Yourself »
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or
older, print "Access granted":
publicclassMain{
staticvoidcheckAge(int age){
if(age <18){
else{
publicstaticvoidmain(String[]args){
New − A new thread begins its life cycle in the new state. It remains in
this state until the program starts the thread. It is also referred to as
a born thread.
Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while
the thread waits for another thread to perform a task. A thread
transitions back to the runnable state only when another thread signals
the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for
a specified interval of time. A thread in this state transitions back to
the runnable state when that time interval expires or when the event it
is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when
it completes its task or otherwise terminates.
Thread Priorities
Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread
priorities cannot guarantee the order in which threads execute and are very
much platform dependent.
As a second step, you will instantiate a Thread object using the following constructor −
Once a Thread object is created, you can start it by calling start() method, which executes a call to
run( ) method. Following is a simple syntax of start() method −
void start();
private Thread t;
private String threadName;
threadName = name;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
if (t == null) {
t.start ();
R1.start();
R2.start();
publicvoidrun()
Step 2: Call Thread using start() Method
Once Thread object is created, you can start it by calling start() method,
which executes a call to run( ) method. Following is a simple syntax of start()
method −
voidstart();
Example: Create Thread by Extending Thread Class
Here is the preceding program rewritten to extend the Thread −
private Thread t;
threadName = name;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
if (t == null) {
t.start ();
T1.start();
T2.start();
Keyword Description
The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the Input/Output
stream classes.
InputStream Class
SN Class Description
The InputStream class provides methods to read bytes from a file, console or memory. It is
an abstract class and can't be instantiated; however, various classes inherit the
InputStream class and override its methods. The subclasses of InputStream class are given
in the following table.
The InputStream class contains various methods to read the data from an input stream.
These methods are overridden by the classes that inherit the InputStream class. However,
the methods are given in the following table.
OutputStream Class
The OutputStream is an abstract class that is used to write 8-bit bytes to the stream. It is the
superclass of all the output stream classes. This class can't be instantiated; however, it is
inherited by various subclasses that are given in the following table.
SN Class Description
Output:
A new file MyNewFile.doc will be created on desktop with the content "Jtp is the best website to learn new
technologies".
However, the CharacterStream classes are mainly used to read characters from the source
and write them to the destination. For this purpose, the CharacterStream classes are
divided into two types of classes, I.e., Reader class and Writer class.
Reader Class
Reader class is used to read the 16-bit characters from the input stream. However, it is an
abstract class and can't be instantiated, but there are various subclasses that inherit the
Reader class and override the methods of the Reader class. All methods of the Reader
class throw an IOException. The subclasses of the Reader class are given in the following
table.
N Class Description
SN Method Description
This method returns the integral
representation of the next
1 int read() character present in the input. It
returns -1 if the end of the input is
encountered.
Writer Class
Writer class is used to write 16-bit Unicode characters to the output stream. The methods of
the Writer class generate IOException. Like Reader class, Writer class is also an abstract
class that cannot be instantiated; therefore, the subclasses of the Writer class are used to
write the characters onto the output stream. The subclasses of the Writer class are given in
the below table.
SN Class Description
To write the characters to the output stream, the Write class provides various methods
given in the following table.
SN Method Description
Collections in Java
he Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store
the elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However,
It is synchronized and contains many methods that are not the part of Collection framework.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that
is used to hold the elements which are about to be processed. There are various classes
like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us to
perform the operations at both the ends.
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
import java.util.*;
public class TestJavaCollection6{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Output:
Gautam
Karan
Ajay
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table
for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends
the HashSet class and implements Set interface. Like HashSet, It also contains unique
elements. It maintains the insertion order and permits null elements.
import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.
The SortedSet can be instantiated as:
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet
is quite fast. The elements in TreeSet stored in ascending order.
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
UNIT 5
Swing is a Java Foundation Classes [JFC] library and an extension of the
Abstract Window Toolkit [AWT]. Java Swing offers much-improved
functionality over AWT, new components, expanded components features,
and excellent event handling with drag-and-drop support.
import java.io.*;
import javax.swing.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating instance of JFrame
JFrame frame = new JFrame();
limitations of AWT
AWT (Abstract Window Toolkit) is a Java library used for building graphical user interfaces
(GUIs). While it has been foundational in Java GUI development, it has several limitations:
Overall, while AWT played a significant role in Java GUI development, its limitations have led
many developers to prefer Swing or JavaFX for building more robust and user-friendly
applications.
MVC Architecture
The Model-View-Controller (MVC) is a well-known design pattern in the web development
field. It is way to organize our code. It specifies that a program or application shall consist of
data model, presentation information and control information. The MVC pattern needs all
these components to be separated as different objects.
In this section, we will discuss the MVC Architecture in Java, alongwith its advantages and
disadvantages and examples to understand the implementation of MVC in Java.
In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests
are processed as follows:
Advantages of MVC Architecture
The advantages of MVC architecture are as follows:
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
o The extending and testing of application is easier.
Let's consider the following code snippet that creates a which is also the first step to
implement MVC pattern.
}
The above code simply consists of getter and setter methods to the Employee class.
View Layer
As the name depicts, view represents the visualization of data received from the model. The
view layer consists of output of application or user interface. It sends the requested data to
the client, that is fetched from model layer by controller.
Let's take an example where we create a view using the EmployeeView class.
Controller Layer
The controller layer gets the user requests from the view layer and processes them, with the
necessary validations. It acts as an interface between Model and View. The requests are
then sent to model for data processing. Once they are processed, the data is sent back to
the controller and then displayed on the view.