0% found this document useful (0 votes)
14 views82 pages

OOPJ

Object oriented programming language

Uploaded by

ruqsanabegum89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views82 pages

OOPJ

Object oriented programming language

Uploaded by

ruqsanabegum89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

UNIT -1 INTRODUCTION TO OOPS CONCEPTS AND CLASSES

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:

 Primitive Data Type


 Non-Primitive Data Type

Primitive Data Types

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

Non-Primitive Data Types:

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

public class IntellipaatClass{


int a; // Instance Variable
static int b; // static variable
void show(){
int c=10; // local variable
}
}

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:

 Unary Operator: Only one operand is required.


 Binary Operator: Two operands required.
 Ternary Operator: Three operands required.

Following are the types of operator depending on the operation:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operator

Arithmetic Operator

 Arithmetic Operators are used to performing an arithmetic operation on the operands.


 Operands used in this can be of the numeric type or string type. Result of the arithmetic
operator is always int or greater than int.

Operator Operator Name Description Example


+ Addition Adds two operands or do string a=1, b= 2
concatenation. a+b=3
OR
String str=”Hello”;
str+10 = Hello10
– Subtraction Subtracts a=1,b= 2
b–a=1
* Multiplication Multiplies a=1,b= 2
a*b=2
/ Divide Perform division operation a=1,b= 2
b/a=2
% Modulus Returns remainder a=1,b= 3
b%a=1
++ Increment First checks the condition, then a=1
Increase the operand value by 1 a++;
a value becomes 2
— Decrement First checks the condition, Decrease a=2
the operand value by 1 a–;
a value becomes 1

Relational Operator

 Relational operators are used to check the relation between the two operands.
 Result of the relational operator is always Boolean value.

Here is the list of relational operators:


Operator Operator Name Description Example
== Equal to Returns true if two operands are a=2, b=2
equal, otherwise returns false if(a== b)
result= true
!= Not Equal to Returns true if two operands are a=2, b=2
not equal, otherwise returns if(a== b)
false result=false
< Less than Checks the lesser value between a=3, b=2
the two operands. if(a<b)
result=false
> Greater than Checks the greater value a=3, b=2
between the two operands. if(a>b)
result= true
<= Less than or equal to If the value of left operand is a=23, b=2
less than or equal to the value of if(a<= b)
right operand then it returns true. result= false
>= Greater than or equal to If the value of left operand is a=22, b=2
greater than or equal to the value if(a>= b)
of right operand then it returns result= true
true.
Logical Operator

 Logical Operators are used to perform logical operations.


 Result of this operator is always a 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

 Assignment Operators are used to assign values to the operand.

Operator Operator Name Description Example


= Assignment It assigns value to left-hand side operand a = 2
It assigns 2 to a
+= Add then assign It performs addition and then result is a+=b means
assigned to left-hand operand a=a+b
-= Subtract then It performs subtraction and then result is a-=b means
assign assigned to left-hand operand a=a–b
*= Multiply then It performs multiplication and then result a*=b means a = a
assign is assigned to left-hand operand. *b
/= Divide then It performs division and then result is a/=b means
assign assigned to left-hand operand a=a/b
%= Modulus then It performs modulus and then result is a%=b means
assign assigned to left-hand operand a=a%b

Bitwise Operators

 Bitwise Operators are used to perform operations on individual bits.

<<= 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.

Syntax: operand1? operand 2:operand3;

 Both the operand must of Boolean type.


 If true, returns operand2, otherwise returns operand3. Example

boolean I = 3>2?true:false; ->returns true.


new Operator
new operator is used to create objects for class.
Example:
class Test{}
class IntellipaatLearn{
public static void main(String args[]){
Test t=new Test(); // t object is created
}
}

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

Interested in learning Java? Enrol in our Java online course now!

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

// Using new Instance

// Main class

classGFG {

// Declaring and initializing string

String name = "GeeksForGeeks";

// Main driver method

publicstaticvoidmain(String[] args)

// Try block to check for exceptions

try{

Class cls = Class.forName("GFG");

// Creating object of main class

// using instance method

GFG obj = (GFG)cls.newInstance();

// Print and display


System.out.println(obj.name);

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 two ways to create a method in Java:


1. Instance Method: Access the instance data using the object name.
Declared inside a class.
Syntax:
// Instance Method
voidmethod_name(){
body // instance area
}
2. Static Method: Access the static data using class name. Declared inside class
with static keyword.
Syntax:
//Static Method
static void method_name(){
body // static area
}

Passing Parameters to a method

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.

Example: pseudo-code for implementing methods


Java

// Define a class
publicclassExample{

// Define instance variables


privateintnumber;
privateStringname;

// Defineaccessor (getter) methods


publicintgetNumber(){
returnnumber;
}

publicStringgetName(){
returnname;
}

// Definemutator (setter) methods


publicvoidsetNumber(intnumber)
{
this.number=number;
}

publicvoidsetName(Stringname){this.name=name;}

// Define other methods


publicvoidprintDetails()
{
System.out.println("Number: "+number);
System.out.println("Name: "+name);
}
}

// Use the methods in another part of the code


Exampleexample=newExample();
example.setNumber(123);
example.setName("GFG Write");
example.printDetails();

There are several advantages to using methods in Java, including:

 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.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending upon
the result of the condition provided. There are two types of decision-making statements in Java, i.e., If
statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or
false. In Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

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.

Syntax of if statement is given below.

if(condition)
{
statement 1; //executes when condition is true
}

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

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
}

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:

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.

Syntax of if-else-if statement is given below.

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
}

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}
else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
4. Nested if-statement

nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.

Syntax of Nested if-statement is given below.

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
}
}

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

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.

The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}

Output:

While using switch statements, we must notice that the case expression will be of the same type as the variable.
However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used.

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to
true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of
the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and
condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we exactly know the number of
times, we want to execute the block of code.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

The flow chart for the for-loop is given below.

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }

Output:

The sum of first 10 natural numbers is 55

Java for-each loop

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.

for(data_type var : array_name/collection_name){


//statements
}

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}

Output:

Printing the content of the array names:

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.

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
} }
}

Output:
Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop

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.

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

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.

Java break statement

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

public class BreakExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

Calculation.java

public class Calculation {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
for(int j = 0; j<=15;j++) {
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
}
}

Output:

0
1
2
3
4
5

Java continue statement

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.

public class ContinueExample {

public static void main(String[] args) {


// TODO Auto-generated method stub

for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

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++.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
ataType arr[];
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
10
20
70
40
50
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.

//Java Program to demonstrate the case of


//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

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

Garbage Collection in Java


Garbage collection in Java is the process by which Java programs perform
automatic memory management. Java programs compile to bytecode that can be run on a
Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are
created on the heap, which is a portion of memory dedicated to the program. Eventually,
some objects will no longer be needed. The garbage collector finds these unused objects
and deletes them to free up memory.

What is Garbage Collection?

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

In Java, a string is a sequence of characters. For example, "hello" is a


string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .

We use double quotes to represent a string in Java. For example,

/ create a string
String type = "Java programming";

Here, we have created a string variable named type . The variable is


initialized with the string Java Programming .

Example: Create a String in Java


classMain{
publicstaticvoidmain(String[] args){

// 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 .

Here, we are directly creating strings like primitive types.


However, there is another way of creating Java strings (using
the new keyword).
Java String Operations
Java provides various string methods to perform different operations on
strings. We will look into some of the commonly used string operations.

1. Get the Length of a String


To find the length of a string, we use the length() method. For example,
classMain{
publicstaticvoidmain(String[] args){

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();

System.out.println("Length: " + length);


}
}

Output

String: Hello! World


Length: 12

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 first string


String first = "Java ";
System.out.println("First String: " + first);

// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);

System.out.println("Joined String: " + joinedString);


}
}

Output

First String: Java


Second String: Programming
Joined String: Java Programming

In the above example, we have created two strings


named first and second . Notice the statement,

String joinedString = first.concat(second);

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.

3. Compare Two Strings


In Java, we can make comparisons between two strings using
the equals() method. For example,
classMain{
publicstaticvoidmain(String[] args){

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = first.equals(second);

System.out.println("Strings first and second are equal: " + result1);

// compare first and third strings


boolean result2 = first.equals(third);

System.out.println("Strings first and third are equal: " + result2);


}
}
Run Code

Output

Strings first and second are equal: true


Strings first and third are equal: false

In the above example, we have created 3 strings named first , second ,

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

The escape character is used to escape some of the characters present


inside a string.

Suppose we need to include double quotes inside a string.

// include double quote


String example = "This is the "String" class";

Since strings are represented by double quotes, the compiler will


treat "This is the " as the string. Hence, the above code will cause an
error.
To solve this issue, we use the escape character \ in Java. For example,

// use the escape character


String example = "This is the \"String\" class.";

Java Strings are Immutable


In Java, strings are immutable. This means once we create a string, we
cannot change that string.
To understand it more thoroughly, consider an example:
// create a string
String example = "Hello! ";

Here, we have created a string variable named example . The variable holds
the string "Hello! " .

Now, suppose we want to change the string.

// add another string "World"


// to the previous tring example
example = example.concat(" World");

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 .

Let's see what has happened here:

1. JVM takes the first string "Hello! "

2. creates a new string by adding "World" to the first string


3. assigns the new string "Hello! World" to the example variable
4. The first string "Hello! " remains unchanged

Creating Strings Using the New Keyword


So far, we have created strings like primitive types in Java.

Since strings in Java are objects, we can create strings using


the new keyword as well. For example,

// create a string using the new keyword


String name = newString("Java String");

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){

// create a string using new


String name = newString("Java String");

System.out.println(name); // print Java String


}
}

Create String Using Literals vs. New Keyword


Now that we know how strings are created using string literals and
the new keyword, let's see what is the major difference between them.
In Java, the JVM maintains a string pool to store all of its strings inside the
memory. The string pool helps in reusing the strings.
1. While creating strings using string literals,

String example = "Java";

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,

String example = newString("Java");

Here, the value of the string is not directly provided. Hence, a


new "Java" string is created even though "Java" is already present inside
the memory pool.
Methods of Java String
Besides those mentioned above, there are various string methods present
in Java. Here are some of those methods:
Methods Description

contains() Checks whether the string contains a substring.

substring() Returns the substring of the string.

join() Joins the given strings using the delimiter.

replace() Replaces the specified old character with the specified new character.

replaceAll() Replaces all substrings matching the regex pattern.

replaceFirst() Replaces the first matching substring.

charAt() Returns the character present in the specified location.

getBytes() Converts the string to an array of bytes.

indexOf() Returns the position of the specified character in the string.

compareTo() Compares two strings in the dictionary order.

compareToIgnoreCase() Compares two strings, ignoring case differences.

trim() Removes any leading and trailing whitespaces.

format() Returns a formatted string.

split() Breaks the string into an array of strings.


toLowerCase() Converts the string to lowercase.

toUpperCase() Converts the string to uppercase.

valueOf() Returns the string representation of the specified argument.

toCharArray() Converts the string to a char array.

matches() Checks whether the string matches the given regex.

startsWith() Checks if the string begins with the given string.

endsWith() Checks if the string ends with the given string.

isEmpty() Checks whether a string is empty or not.

intern() Returns the canonical representation of the string.

contentEquals() Checks whether the string is equal to charSequence.

hashCode() Returns a hash code for the string.

subSequence() Returns a subsequence from the string.

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.

Here are the main types of inheritance:

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;

// the Bicycle class has one constructor


publicBicycle(intgear,intspeed)
{
this.gear=gear;
this.speed=speed;
}

// the Bicycle class has three methods


publicvoidapplyBrake(intdecrement)
{
speed-=decrement;
}

publicvoidspeedUp(intincrement)
{
speed+=increment;
}

// toString() method to print info of Bicycle


publicStringtoString()
{
return("No of gears are "+gear+"\n"
+"speed of bicycle is "+speed);
}
}

// derived class
classMountainBikeextendsBicycle{

// the MountainBike subclass adds one more field


publicintseatHeight;

// the MountainBike subclass has one constructor


publicMountainBike(intgear,intspeed,
intstartHeight)
{
// invoking base-class(Bicycle) constructor
super(gear,speed);
seatHeight=startHeight;
}

// the MountainBike subclass adds one more method


publicvoidsetHeight(intnewValue)
{
seatHeight=newValue;
}

// overriding toString() method


// of Bicycle to print more info
@OverridepublicStringtoString()
{
return(super.toString()+"\nseat height is "
+seatHeight);
}
}

// 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.

o Method overriding is used to provide the specific implementation of a method which


is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method are the same, and there is IS-A relationship between the classes, so there is
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");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
} }
A real example of Java Method Overriding

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 categorize

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.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package
The package keyword is used to create a package in java.

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.

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation
is provided in the A6 class.

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).

Java try and catch


The try statement allows you to define a block of code to be tested for errors
while it is being executed.

The catch statement allows you to define a block of code to be executed, if


an error occurs in the try block.

The try and catch keywords come in pairs:

SyntaxGet your own Java Server


try{

// Block of code to try

catch(Exceptione){

// Block of code to handle errors

publicclassMain{

publicstaticvoidmain(String[]args){

int[]myNumbers={1,2,3};

System.out.println(myNumbers[10]);// error!

}
The output will be something like this:

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)

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){

System.out.println("Something went wrong.");

}finally{

System.out.println("The 'try catch' is finished.");

The output will be:

Something went wrong.


The 'try catch' is finished.

Try it Yourself »

The throw keyword


The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are
many exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBound
sException, SecurityException, etc:

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){

thrownewArithmeticException("Access denied - You must be at least 18


years old.");

else{

System.out.println("Access granted - You are old enough!");

publicstaticvoidmain(String[]args){

checkAge(15);// Set age to 15 (which is below 18...)

The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access


denied - You must be at least 18 years old.
atMain.checkAge(Main.java:4)
at Main.main(Main.java:12)
Java Multithreading
Multi-threading enables you to write in a way where multiple activities can
proceed concurrently in the same program. To achieve the multithreading
(or, write multithreaded code), you need java.lang.Thread class.

Life Cycle of a Thread in Java Multithreading


A thread goes through various stages in its life cycle. For example, a thread
is born, started, runs, and then dies. The following diagram shows the
complete life cycle of a thread.

Following are the stages of the life cycle −

 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.

Java thread priorities are in the range between MIN_PRIORITY (a constant of


1) and MAX_PRIORITY (a constant of 10). By default, every thread is given
priority NORM_PRIORITY (a constant of 5).

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.

Create a Thread by Implementing a Runnable Interface


If your class is intended to be executed as a thread then you can achieve this
by implementing a Runnable interface. You will need to follow three basic
steps −

Step 1: Implement run() Method


As a first step, you need to implement a run() method provided by
a Runnable interface. This method provides an entry point for the thread and
you will put your complete business logic inside this method. Following is a
simple syntax of the run() method −

public void run( )

Step 2: Instantiate a Thread Object

As a second step, you will instantiate a Thread object using the following constructor −

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnable interface


and threadName is the name given to the new thread.

Step 3: Call Thread using start() Method

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();

classRunnableDemo implements Runnable {

private Thread t;
private String threadName;

RunnableDemo( String name) {

threadName = name;

System.out.println("Creating " + threadName );

public void run() {

System.out.println("Running " + threadName );

try {

for(inti = 4; i> 0; i--) {

System.out.println("Thread: " + threadName + ", " + i);

// Let the thread sleep for a while.

Thread.sleep(50);

} catch (InterruptedException e) {

System.out.println("Thread " + threadName + " interrupted.");

System.out.println("Thread " + threadName + " exiting.");

public void start () {

System.out.println("Starting " + threadName );

if (t == null) {

t = new Thread (this, threadName);

t.start ();

public class TestThread {


public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");

R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");

R2.start();

Create a Thread by Extending a Thread Class


The second way to create a thread is to create a new class that
extends Thread class using the following two simple steps. This approach
provides more flexibility in handling multiple threads created using available
methods in Thread class.

Step 1: Override run() Method


You will need to override run( ) method available in Thread class. This method
provides an entry point for the thread and you will put your complete
business logic inside this method. Following is a simple syntax of run()
method −

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 −

classThreadDemo extends Thread {

private Thread t;

private String threadName;


ThreadDemo( String name) {

threadName = name;

System.out.println("Creating " + threadName );

public void run() {

System.out.println("Running " + threadName );

try {

for(inti = 4; i> 0; i--) {

System.out.println("Thread: " + threadName + ", " + i);

// Let the thread sleep for a while.

Thread.sleep(50);

} catch (InterruptedException e) {

System.out.println("Thread " + threadName + " interrupted.");

System.out.println("Thread " + threadName + " exiting.");

public void start () {

System.out.println("Starting " + threadName );

if (t == null) {

t = new Thread (this, threadName);

t.start ();

public class TestThread {


public static void main(String args[]) {

ThreadDemo T1 = new ThreadDemo( "Thread-1");

T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2");

T2.start();

Keyword Description

try The "try" keyword is used to specify a


block where we should place an exception
code. It means we can't use try block
alone. The try block must be followed by
either catch or finally.

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


necessary code of the program. It is
executed whether an exception is handled
or not.

throw The "throw" keyword is used to throw an


exception.

throws The "throws" keyword is used to declare


exceptions. It specifies that there may
occur an exception in the method. It
doesn't throw an exception. It is always
used with method signature.

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
UNIT 4
ByteStream Classes in Java
ByteStream classes are used to read bytes from the input stream and write bytes to the
output stream. In other words, we can say that ByteStream classes read/write the data of 8-
bits. We can store video, audio, characters, etc., by using ByteStream classes. These
classes are part of the java.io package.

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

This class provides methods to


1 BufferedInputStream
read bytes from the buffer.

This class provides methods to


2 ByteArrayInputStream
read bytes from the byte array.

This class provides methods to


3 DataInputStream
read Java primitive data types.

This class provides methods to


4 FileInputStream
read bytes from a file.

This class contains methods to


read bytes from the other input
5 FilterInputStream
streams, which are used as the
primary source of data.

This class provides methods to


6 ObjectInputStream
read objects.

This class provides methods to


read from a piped output stream
7 PipedInputStream
to which the piped input stream
must be connected.

This class provides methods to


8 SequenceInputStream connect multiple Input Stream
and read data from them.

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

This class provides methods to


1 BufferedOutputStream
write the bytes to the buffer.

This class provides methods to


2 ByteArrayOutputStream
write bytes to the byte array.

This class provides methods to


3 DataOutputStream
write the java primitive data types.

This class provides methods to


4 FileOutputStream
write bytes to a file.

This class provides methods to


5 FilterOutputStream
write to other output streams.

This class provides methods to


6 ObjectOutputStream
write objects.

It provides methods to write bytes


7 PipedOutputStream
to a piped output stream.

It provides methods to print Java


8 PrintStream
primitive data types.
Example:
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class InputOutputStreamExample {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
byte content[] = "Jtp is the best website to learn new technologies".getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
inputStream.read(content);
File newFile = new File("/Users/MyUser/Desktop/MyNewFile.doc");
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(content);
}
}

Output:

A new file MyNewFile.doc will be created on desktop with the content "Jtp is the best website to learn new
technologies".

CharacterStream Classes in Java


The java.io package provides CharacterStream classes to overcome the limitations of
ByteStream classes, which can only handle the 8-bit bytes and is not compatible to work
directly with the Unicode characters. CharacterStream classes are used to work with 16-bit
Unicode characters. They can perform operations on characters, char arrays and Strings.

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

This class provides methods to


1. BufferedReader
read characters from the buffer.

This class provides methods to


2. CharArrayReader read characters from the char
array.

This class provides methods to


3. FileReader
read characters from the file.

This class provides methods to


4. FilterReader read characters from the
underlying character input stream.

This class provides methods to


5 InputStreamReader
convert bytes to characters.

This class provides methods to


6 PipedReader read characters from the
connected piped output stream.

This class provides methods to


7 StringReader
read characters from a string.

The Reader class methods are given in the following table.

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.

This method is used to read from


the specified buffer. It returns the
total number of characters
2 int read(char buffer[])
successfully read. It returns -1 if
the end of the input is
encountered.

This method is used to read the


specified nChars from the buffer at
int read(char buffer[], int loc, int
3 the specified location. It returns the
nChars)
total number of characters
successfully read.

This method is used to mark the


4 void mark(int nchars) current position in the input stream
until nChars characters are read.

This method is used to reset the


5 void reset() input pointer to the previous set
mark.

This method is used to skip the


specified nChars characters from
6 long skip(long nChars)
the input stream and returns the
number of characters skipped.

This method returns a boolean


value true if the next request of
7 boolean ready()
input is ready. Otherwise, it returns
false.
This method is used to close the
input stream. However, if the
8 void close()
program attempts to access the
input, it generates IOException.

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

This class provides methods to


1 BufferedWriter
write characters to the buffer.

This class provides methods to


2 FileWriter
write characters to the file.

This class provides methods to


3 CharArrayWriter write the characters to the
character array.

This class provides methods to


4 OutpuStreamWriter
convert from bytes to characters.

This class provides methods to


5 PipedWriter write the characters to the piped
output stream.

This class provides methods to


6 StringWriter
write the characters to the string.

To write the characters to the output stream, the Write class provides various methods
given in the following table.
SN Method Description

This method is used to write the


1 void write()
data to the output stream.

This method is used to write a


2 void write(int i) single character to the output
stream.

This method is used to write the


3 Void write(char buffer[]) array of characters to the output
stream.

This method is used to write the


void write(char buffer [],int loc, int
4 nChars characters to the character
nChars)
array from the specified location.

This method is used to close the


output stream. However, this
generates the IOException if an
5 void close ()
attempt is made to write to the
output stream after closing the
stream.

This method is used to flush the


6 void flush () output stream and writes the
waiting buffered characters.

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).

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework


The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:

No. Method Description

It is used to insert an element in


1 public boolean add(E e)
this collection.

2 It is used to insert the specified


public boolean addAll(Collection<?
collection elements in the invoking
extends E> c) collection.

public boolean remove(Object It is used to delete an element


3
element) from the collection.

It is used to delete all the elements


public boolean
4 of the specified collection from the
removeAll(Collection<?> c)
invoking collection.

default boolean It is used to delete all the elements


5 removeIf(Predicate<? super E> of the collection that satisfy the
filter) specified predicate.

It is used to delete all the elements


public boolean
6 of invoking collection except the
retainAll(Collection<?> c)
specified collection.

It returns the total number of


7 public int size()
elements in the collection.

It removes the total number of


8 public void clear()
elements from the collection.

public boolean contains(Object


9 It is used to search an element.
element)

public boolean It is used to search the specified


10
containsAll(Collection<?> c) collection in the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

It converts collection into array.


13 public <T> T[] toArray(T[] a) Here, the runtime type of the
returned array is that of the
specified array.

14 public boolean isEmpty() It checks if collection is empty.

It returns a possibly parallel


default Stream<E>
15 Stream with the collection as its
parallelStream()
source.

It returns a sequential Stream with


16 default Stream<E> stream()
the collection as its source.

It generates a Spliterator over the


17 default Spliterator<E> spliterator() specified elements in the
collection.

public boolean equals(Object


18 It matches two collections.
element)

It returns the hash code number of


19 public int hashCode()
the collection.

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.

Consider the following example.

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.

Consider the following example.

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.

Consider the following example.

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.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given
below.

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.

Consider the following example.

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.

Deque can be instantiated as:

Deque d = new ArrayDeque();

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.

Consider the following example.

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.

Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();


Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();

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.

Consider the following example.

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.

Consider the following example.

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:

SortedSet<data-type> set = new TreeSet();

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.

Consider the following example:

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.

Introduction of Java Swing


Swing has about four times the number of User Interface [UI] components as
AWT and is part of the standard Java distribution. By today’s application GUI
requirements, AWT is a limited implementation, not quite capable of
providing the components required for developing complex GUIs required in
modern commercial applications. The AWT component set has quite a few
bugs and does take up a lot of system resources when compared to
equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUI’s for commercial applications.
 Swing is a Set of API (API- Set of Classes and Interfaces)
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the
looks and Functionality of GUIs’
 Swing can be used to build (Develop) The Standalone swing GUI Apps as
Servlets and Applets
 It Employs model/view design architecture.
 Swing is more portable and more flexible than AWT, the Swing is built on
top of the AWT.
 Swing is Entirely written in Java.
 Java Swing Components are Platform-independent, and The Swing
Components are lightweight.
 Swing Supports a Pluggable look and feel and Swing provides more
powerful components.
 such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
 Further Swing Follows MVC.

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();

// Creating instance of JButton


JButton button = new JButton(" GFG WebSite Click");

// x axis, y axis, width, height


button.setBounds(150, 200, 220, 50);

// adding button in JFrame


frame.add(button);

// 400 width and 500 height


frame.setSize(500, 600);

// using no layout managers


frame.setLayout(null);

// making the frame visible


frame.setVisible(true);
}
}

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:

1. Heavyweight Components: AWT components are considered heavyweight because they


rely on the native system's GUI components. This can lead to inconsistent appearances
across different platforms.
2. Limited Components: AWT provides a limited set of components compared to more
modern frameworks like Swing or JavaFX. This can make it challenging to create
complex UIs.
3. Event Handling Complexity: AWT's event handling model can be cumbersome and less
intuitive compared to newer frameworks, which offer more flexible and straightforward
event handling mechanisms.
4. Platform Dependency: Because AWT uses native GUI components, applications may
behave differently on different platforms, leading to portability issues.
5. Lack of Advanced Features: AWT lacks many advanced features found in Swing and
JavaFX, such as pluggable look-and-feel, rich text, and more sophisticated graphics
capabilities.
6. Performance Issues: Since AWT components are heavyweight, they can be slower to
render and less efficient than lightweight components used in Swing or JavaFX.
7. Limited Customization: Customizing AWT components can be challenging, as they do
not support the same level of customization as Swing or JavaFX components.
8. Obsolescence: With the introduction of Swing and JavaFX, AWT is often seen as
outdated, and its usage has declined in favor of more modern frameworks.

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.

What is MVC architecture in Java?


The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using
model designs.

The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object to carry the


data that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the
data that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever
data is changed.

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.

Implementation of MVC using Java


To implement MVC pattern in Java, we are required to create the following three classes.

o Employee Class, will act as model layer


o EmployeeView Class, will act as a view layer
o EmployeeContoller Class, will act a controller layer

MVC Architecture Layers


Model Layer
The Model in the MVC design pattern acts as a data layer for the application. It represents
the business logic for application and also the state of application. The model object fetch
and store the model state in the database. Using the model layer, rules are applied to the
data that represents the concepts of application.

Let's consider the following code snippet that creates a which is also the first step to
implement MVC pattern.

// class that represents model


public class Employee {

// declaring the variables


private String EmployeeName;
private String EmployeeId;
private String EmployeeDepartment;

// defining getter and setter methods


public String getId() {
return EmployeeId;
}

public void setId(String id) {


this.EmployeeId = id;
}
public String getName() {
return EmployeeName;
}

public void setName(String name) {


this.EmployeeName = name;
}

public String getDepartment() {


return EmployeeDepartment;
}

public void setDepartment(String Department) {


this.EmployeeDepartment = Department;
}

}
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.

// class which represents the view


public class EmployeeView {

// method to display the Employee details


public void printEmployeeDetails (String EmployeeName, String EmployeeId,
String EmployeeDepartment){
System.out.println("Employee Details: ");
System.out.println("Name: " + EmployeeName);
System.out.println("Employee ID: " + EmployeeId);
System.out.println("Employee Department: " + EmployeeDepartment);
}
}

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.

public class EmployeeController {


// declaring the variables model and view
private Employee model;
private EmployeeView view;
// constructor to initialize
public EmployeeController(Employee model, EmployeeView view) {
this.model = model;
this.view = view;
}

// getter and setter methods


public void setEmployeeName(String name){
model.setName(name);
}

public String getEmployeeName(){


return model.getName();
}

public void setEmployeeId(String id){


model.setId(id);
}

public String getEmployeeId(){


return model.getId();
}

public void setEmployeeDepartment(String Department){


model.setDepartment(Department);
}

public String getEmployeeDepartment(){


return model.getDepartment();
}

// method to update view


public void updateView() {
view.printEmployeeDetails(model.getName(), model.getId(), model.getDepartmet(
));
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy