java honors
java honors
java honors
Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in
programming. The main aim of OOPs 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.
OOPS concepts are as follows:
● Class
● Object
● Method and method passing
Pillars of OOPs:
● Abstraction
● Encapsulation
● Inheritance
● Polymorphism
○ Compile-time polymorphism
○ Runtime polymorphism
Class:
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or
methods that are common to all objects of one type. Using classes, you can create multiple objects with the same behavior instead
of writing their code multiple times. This includes classes for objects occurring more than once in your code. In general, class
declarations can include these components in order:
Modifiers: A class can be public or have default access (Refer to this for details).
Class name: The class name should begin with the initial letter capitalized by convention.
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A
class can implement more than one interface.
Body: The class body is surrounded by braces, { }.
An object is a basic unit of Object-Oriented Programming that represents real-life entities. A typical Java program creates
many objects, which as you know, interact by invoking methods. The objects are what perform your code, they are the part of your
code visible to the viewer/user. An object mainly consists of:
Example Program of Class:-
public class College {
class Employee {
private int empid;
private String ename;
}
Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by which one class is allowed
to inherit the features (fields and methods) of another class. We are achieving inheritance by using extends keyword. Inheritance is
also known as “is-a” relationship.
Superclass: The class whose features are inherited is known as superclass (also known as base or parent class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or child class).
The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already
a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Below are some of the differences between procedural and object-oriented programming:
In procedural programming, the program is divided into small In object-oriented programming, the program is divided into
parts called functions. small parts called objects.
There is no access specifier in procedural programming. Object-oriented programming has access specifiers like
private, public, protected, etc.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any proper way of hiding Object-oriented programming provides data hiding so it is
data so it is less secure. more secure.
In procedural programming, there is no concept of data hiding and In object-oriented programming, the concept of data hiding
inheritance. and inheritance is used.
In procedural programming, the function is more important than In object-oriented programming, data is more important
the data. than function.
Procedural programming is based on the unreal world. Object-oriented programming is based on the real world.
Procedural programming is used for designing medium-sized Object-oriented programming is used for designing large
programs. and complex programs.
Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.
Code reusability absent in procedural programming, Code reusability present in object-oriented programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
—---------------------------------------
Java Programming
A First Simple Program
Now that the basic object-oriented underpinning of Java has been discussed, let’s look at some actual Java programs. Let’s start by
compiling and running the short sample program shown here. As you will see, this involves a little more work than you might
imagine.
/* This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}}
For most computer languages, the name of the file that holds the source code to a program is immaterial. However, this is
not the case with Java.
The first thing that you must learn about Java is that the name you give to a source file is very important.
For this example, the name of the source file should be Example.java. Let’s see why. In Java, a source file is officially
called a compilation unit.
It is a text file that contains (among other things) one or more class definitions. (For now, we will be using source files that
contain only one class.)
The Java compiler requires that a source file use the .java filename extension. As you can see by looking at the program,
the name of the class defined by the program is also Example.
This is not a coincidence. In Java, all code must reside inside a class. By convention, the name of the main class should
match the name of the file that holds the program.
You should also make sure that the capitalization of the filename matches the class name. The reason for this is that Java
is case-sensitive.
At this point, the convention that filenames correspond to class names may seem arbitrary. However, this convention
makes it easier to maintain and organize your programs.
Compiling the Program To compile the Example program, execute the compiler, javac, specifying the name of the source
file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of the program. As discussed earlier, the
Java bytecode is the intermediate representation of your program that contains instructions the Java Virtual Machine will execute.
Thus, the output of javac is not code that can be directly executed.
To actually run the program, you must use the Java application launcher called java. To do so, pass the class name
Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
This is a simple Java program.
The Java Keywords
Datatypes:-
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
The primitive types are also commonly referred to as simple types, and both terms will be used in this book. These can be put in
four groups:
• Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers.
•Floating-point numbers This group includes float and double, which represent numbers with fractional precision.
•Characters This group includes char, which represents symbols in a character set, like letters and numbers.
•Boolean This group includes boolean, which is a special type for representing true/false values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does
not support unsigned, positive-only integers.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are
especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with
raw binary data that may not be directly compatible with Java’s other built-in types.
Byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called b
and c:
byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the leastused Java type. Here are some
examples of short variable declarations:
short s;
short t;
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired
value. The range of a long is quite large. This makes it useful when big, whole numbers are needed
int lightspeed;
long days;
long seconds;
long distance;
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional
precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose
precision requires a floating point type.
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors
and takes half as much space as double precision, but will become imprecise when the values are either very large or very small.
Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision.
For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than
single precision on some modern processors that have been optimized for high-speed mathematical calculations. All
transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over
many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle: // Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a; r = 10.8;
// radius of circle pi = 3.1416;
// pi, approximately
a = pi * r * r;
// compute area
System.out.println("Area of circle is " + a);
}}
Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the
same as char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java.Instead, Java uses Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages.
Unicode required 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The
standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1,
ranges from 0 to 255.
Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2; ch1 = 88;
// code for X ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}}
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the
type returned by all relational operators, as in the case of a < b. boolean is also the type required by the conditional expressions
that govern the control statements such as if and for.
Here is a program that demonstrates the boolean type :
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}}
Escape Sequence Characters:
Type casting
Converting a value from one data type to another data type is known as type casting.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
In the above example, we have taken a variable x and converted it into a long type. After that, the long type is converted into the
float type.
double -> float -> long -> int -> char -> short -> byte
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times. First, we have converted the double type into
long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Accepting Input from the Keyboard, Reading Input with Java.util.Scanner Class
This statement declares a reference variable named console. The Scanner object is associated with the standard input
device (System.in).
To get input from the keyboard, you can call methods of the Scanner class. For example in following statement nextInt()
method of Scanner takes an integer and returns to variable x :
int x = console.nextInt();
Example :
/**
* This program demonstrates keyboard input.
*/
public class RectangleArea
{
public static void main(String[] args)
{
int length; // To hold the rectangle's length.
int width; // To hold the rectangle's width.
int area; // To hold rectangle's area
// Calculate area.
area = length * width;
// Display area.
System.out.println("The area of rectangle is " + area);
}
}
Output :
Enter length 5
Enter width 8
The area of rectangle is 40
Method Returns
String next() Finds and returns the next complete token as a string ended by a blank.
String nextLine() Returns the rest of the current line, excluding any line separator at the end.
printf() uses format specifiers for formatting. There are certain data types are mentioned below:
The number itself includes Integer, Long, etc. The formatting Specifier used is %d.
Below is the implementation of the above method:
// Driver Class
class College {
// main function
public static void main (String[] args) {
int a=10000;
//System.out.printf("%.d%n",a);
System.out.printf("%,d%n",a);
}
}
Output
10,000
ii). For Decimal Number Formatting
Decimal Number Formatting can be done using print() and format specifier %f .
Below is the implementation of the above method:
// Java Programs to demonstrate
// Use of Printf() for decimal
// Number Formatting
import java.io.*;
// Driver Class
class College {
// main function
public static void main(String[] args)
{
// declaring double
double a = 3.14159265359;
Output
3.141593
3.142
3.14
// Driver Function
class College {
// main function
public static void main(String[] args)
{
int a = 10;
Boolean b = true, c = false;
Integer d = null;
// Driver Class
class College {
// main function
public static void main(String[] args)
{
char c = 'g';
// Formatting Done
System.out.printf("%c\n", c);
// Driver Class
class College {
// main function
public static void main(String[] args)
{
String str = "College";
str = "College";
// Vice-versa not possible
System.out.printf("%S \n", str);
System.out.printf("%s \n", str);
}
}
Output
College
College
College
College
// Driver Class
class College {
// main function
public static void main(String[] args)
{
Date time = new Date();
In Java, String format() method returns a formatted string using the given locale, specified format string, and arguments.
We can concatenate the strings using this method and at the same time, we can format the output concatenated string.
// Main class
class College {
// Main driver method
public static void main(String args[])
{
// Custom input string to be formatted
String str = "College";
Control Statements
A programming language uses control statements to control the flow of execution of a program based on certain conditions. These
are used to cause the flow of execution to advance and branch based on changes to the state of a program.
if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return
1. if: if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of
statements will be executed or not i.e if a certain condition is true then a block of statements is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the block
of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by
default if statement will consider the immediate one statement to be inside
its block. For example,
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("Inside If block"); // part of if block(immediate one statement after if condition)
System.out.println("10 is less than 15"); //always executes as it is outside of if block
// This statement will be executed
// as if considers one statement by default again below statement is outside of if block
System.out.println("I am Not in if");
}
}
Output
Inside If block
10 is less than 15
I am Not in if
Time Complexity: O(1)
Auxiliary Space : O(1)
2. if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it
won’t. But what if we want to do something else if the condition is false? Here comes the else statement. We can use the else
statement with the if statement to execute a block of code when the condition
is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
class IfElseDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output
i is smaller than 15
Time Complexity: O(1)
Auxiliary Space : O(1)
3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside
an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can
place an if statement inside another if
statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
class NestedIfDemo {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i<15) {
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println(
"i is smaller than 12 too");
} else{
System.out.println("i is greater than 15");
}
}
}
Output
i is smaller than 15
i is smaller than 12 too
Time Complexity: O(1)
Auxiliary Space: O(1)
4. if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as
one of the conditions controlling the if is true, the statement associated with that ‘if’ is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will
be executed. There can be as many as ‘else if’ blocks associated with one ‘if’
block but only one ‘else’ block is allowed with one ‘if’ block.
if (condition)
statement;
else if (condition)
statement;
.
.
else
Statement;
class ifelseifDemo {
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output
i is 20
Time Complexity: O(1)
Auxiliary Space: O(1)
5. switch-case: The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different
parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
/*package whatever //do not write package name here */
import java.io.*;
class College {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : System.out.println("It is 5");
break;
case 10 : System.out.println("It is 10");
break;
case 15 : System.out.println("It is 15");
break;
case 20 : System.out.println("It is 20");
break;
default: System.out.println("Not present");
}
}
}
Output
It is 20
Time Complexity: O(1)
Space Complexity: O(1)
The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7, the expression can also be of type
String.
Duplicate case values are not allowed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
The break statements are necessary without the break keyword, statements in switch blocks fall through.
If the break keyword is omitted, execution will continue to the next case.
6. jump: Java supports three jump statements: break, continue and return. These three statements transfer control to another part
of the program.
class ContinueDemo {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
if (i % 2 == 0)
continue;
Return: The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the
caller of the method.
if (t)
return;
UNIT - II
Arrays
-- type var-name[];
-- type[] var-name;
An array declaration has two components: the type and the name. type declares the element type of the array. The element type
determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other
primitive data types like char, float, double, etc., or user-defined data types (objects of a class). Thus, the element type for the array
determines what type of data the array will hold.
Example:
// both are valid declarations
int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;
// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard
output.
class College {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
import java.io.*;
class College {
public static void main (String[] args) {
System.out.println("Array Size:"+arr.length);
}
}
Output
Array Size:4
ArrayIndexOutOfBoundsException
JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of an array.
System.out.println(
"Trying to access element outside the size of array");
System.out.println(arr[5]);
}
}
Output
// Driver class
class College {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column
// Number of Rows
System.out.println("Number of Rows:"+
arr.length);
// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}
Output
Number of Rows:3
Number of Columns:3
Multidimensional Array Declaration
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output
279
361
742
Passing Arrays to Methods
Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate
the sum of the array’s values.
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
String Class Methods
The string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed
once created.
Creating a String
There are two ways to create string in Java:
1. String literal
String s = “College”;
2. Using new keyword
String s = new String (“College”);
String Constructors in Java
1. String(byte[] byte_arr)
Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s_byte =new String(b_arr); //Geeks
2. String(byte[] byte_arr, Charset char_set)
Construct a new String by decoding the byte array. It uses the char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs); //Geeks
3. String(byte[] byte_arr, String char_set_name)
Construct a new String by decoding the byte array. It uses the char_set_name for decoding. It looks similar to the above
constructs and they appear before similar functions but it takes the String(which contains char_set_name) as parameter while the
above constructor takes CharSet.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, "US-ASCII"); //Geeks
4. String(byte[] byte_arr, int start_index, int length)
Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 3); // eek
5. String(byte[] byte_arr, int start_index, int length, Charset char_set)
Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs); // eek
6. String(byte[] byte_arr, int start_index, int length, String char_set_name)
Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set_name for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks
7. String(char[] char_arr)
Allocates a new String from the given Character array
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr); //Geeks
8. String(char[] char_array, int start_index, int count)
Allocates a String from a given character array but choose count characters from the start_index.
Example:
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr , 1, 3); //eek
9. String(int[] uni_code_points, int offset, int count)
Allocates a String from a uni_code_array but choose count characters from the start_index.
Example:
int[] uni_code = {71, 101, 101, 107, 115};
String s = new String(uni_code, 1, 3); //eek
10. String(StringBuffer s_buffer)
Allocates a new string from the string in s_buffer
Example:
StringBuffer s_buffer = new StringBuffer("Geeks");
String s = new String(s_buffer); //Geeks
11. String(StringBuilder s_builder)
Allocates a new string from the string in s_builder
Example:
StringBuilder s_builder = new StringBuilder("Geeks");
String s = new String(s_builder); //Geeks
import java.io.*;
import java.util.*;
class Test
{
// main function
public static void main (String[] args)
{
String s= "College";
System.out.println("String length = " + s.length());
System.out.println("Character at 3rd position = " + s.charAt(3));
System.out.println("Substring" + s.substring(3));
System.out.println("Substring= " + s.substring(2,5));
String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string= " +s1.concat(s2));
String s4 = "Learn Share Learn";
System.out.println("Index of Share " +s4.indexOf("Share"));
System.out.println("Index of a= " +s4.indexOf('a',3));
Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality" + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality" + out);
out = "Geeks".equalsIgnoreCase("gEeks ");
System.out.println("Checking Equality " + out);
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +word1.toLowerCase());
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +word2.toUpperCase());
String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}
Output
String length = 13
Character at 3rd position = k
SubstringksforGeeks
Substring= eks
Concatenated string= College
Index of Share 6
Index of a= 8
Checking Equalityfalse
Checking Equalitytrue
Checking Equality false
the difference between ASCII value is=-31
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks
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.
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. Objects are the
instances of a class that are created to use the attributes and methods of a class. A typical Java program creates many objects,
which as you know, interact by invoking methods. An object consists of :
Example:
As we declare variables like (type name;). This notifies the
compiler that we will use the name to refer to data whose type is
type. With a primitive variable, this declaration also reserves the
proper amount of memory for the variable. So for reference
variables , the type must be strictly a concrete class name. In
general, we can’t create objects of an abstract class or an
interface.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned
to it. Simply declaring a reference variable does not create an object.
Initializing a Java object
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new
operator also invokes the class constructor.
Class Object
No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.
Types of parameters:
Formal Parameter: A variable and its type as they appear in the prototype of the function or method.
Syntax:
function_name(datatype variable_name)
Actual Parameter: The variable or expression corresponding to a formal parameter that appears in the function or method call in
the calling environment.
Syntax:
func_name(variable name(s));
// Callee
class CallByValue {
// Caller
public class Main {
public static void main(String[] args)
{
int a = 10;
int b = 20;
System.out.println("Value of a: " + a
+ " & b: " + b);
Output
Value of a: 10 & b: 20
Value of a: 10 & b: 20
2. Call by reference(aliasing):
Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the
formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or
pointer) to the actual data. This method is also called as call by reference. This method is efficient in both time and space.
// Java program to illustrate
// Call by Reference
// Callee
class CallByReference {
int a, b;
// Caller
public class Main {
// Displaying values
// after calling the function
System.out.println("Value of a: " + object.a
+ " & b: " + object.b);
}
}
Output
Value of a: 10 & b: 20
Value of a: 20 & b: 40
—---------
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
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.
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.
Syntax:
//Static Method
static void method_name(){
body // static area
}
this keyword:
In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a keyword that refers
to the current object instance. It can be used to call current class methods and fields, to pass an instance of the current class as a
parameter, and to differentiate between the local and instance variables. Using “this” reference can improve code readability and
reduce naming conflicts.
import java.io.*;
class Test {
public static int i = 0;
Test()
{
i++;
}
public static int get()
{
return i;
}
public int m1()
{
class College {
public static void main(String[] args)
{
Test obj = new Test();
int i = obj.m1();
System.out.println( "Control returned after method m1 :" + i);
Output
Inside the method m1 by object of College class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1
—---------------
Java Constructors
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.
// Driver Class
class Geeks {
// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}
// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
}
Output
Constructor Called
class Geek
{
.......
// A Constructor
Geek() {
}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded
constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super
at the first line of your code, the super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the subclass of a class object even if you don’t
say extends object in your class definition.
Default Constructor
Parameterized Constructor
Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write
a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called
a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor
can’t change the default constructor. The default constructor can be implicit or explicit. If we don’t define explicitly, we get an implicit
default constructor. If we manually write a constructor, the implicit one is overridded.
// Driver class
class College {
// Default Constructor
College() { System.out.println("Default constructor"); }
// Driver function
public static void main(String[] args)
{
College hello = new College();
}
}
Output
Default constructor
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our
own values, then use a parameterized constructor.
Output
GeekName :Avinash and GeekId :68
class Geek {
// data members of the class.
String name;
int id;
// Parameterized Constructor
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
// Copy Constructor
Geek(Geek obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class College {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
System.out.println();
Output
First Object
GeekName :Avinash and GeekId :68
—---------
Method Overloading
In Java, Method Overloading allows different methods to have the same name, but different signatures where the
signature can differ by the number of input parameters or type of input parameters, or a mixture of both.
Method overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism, or Early binding. In
Method overloading compared to the parent argument, the child argument will get the highest priority.
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output
30
60
31.0
—-------
Inheritance
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by which one
class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes
based on existing ones. A class that inherits from another class can reuse the methods and fields of that class. In addition, you can
add new fields and methods to your current class as well.
import java.io.*;
// Driver Class
class College {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "\nBenefits : " + E1.benefits);
}
}
Output
Salary : 60000
Benefits : 10000
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a
single-parent class. Sometimes, it is also known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child
class. The class ‘B’ inherits all the properties of the class ‘A’.
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}
// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output
Geeks
for
Geeks
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as the
base class for other classes. In the below image, class A serves as a base class for the derived class B, which in turn serves as a
base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
Output
Geeks
for
Geeks
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image,
class A serves as a base class for the derived classes B, C, and D.
class A {
public void print_A() { System.out.println("Class A"); }
}
class B extends A {
public void print_B() { System.out.println("Class B"); }
}
class C extends A {
public void print_C() { System.out.println("Class C"); }
}
class D extends A {
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
Output
Class A
Class B
Class A
Class C
Class A
Class D
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please
note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through
Interfaces. In the image below, Class C is derived from interfaces A and B.
interface One {
public void print_geek();
}
interface Two {
public void print_for();
}
// Drived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output
Geeks
for
Geeks
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple inheritance
is also not possible with classes. In Java, we can achieve hybrid inheritance only through
Interfaces if we want to involve multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the use
of Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel
Inheritance and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance
with classes. Therefore, it is indeed possible to implement Hybrid inheritance using classes
alone, without relying on multiple inheritance type.
Super Keyword
The super keyword in Java is a reference variable that is used to refer to parent class when we’re working with objects.
You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword.
The Keyword “super” came into the picture with the concept of Inheritance. In this article, we gonna covers all about super
in Java including definitions, examples, Uses, Syntax, and more.
super is used to call a superclass constructor: When a subclass is created, its constructor must call the constructor of its
parent class. This is done using the super() keyword, which calls the constructor of the parent class.
super is used to call a superclass method: A subclass can call a method defined in its parent class using the super
keyword. This is useful when the subclass wants to invoke the parent class’s implementation of the method in addition to its own.
super is used to access a superclass field: A subclass can access a field defined in its parent class using the super
keyword. This is useful when the subclass wants to reference the parent class’s version of a field.
super must be the first statement in a constructor: When calling a superclass constructor, the super() statement must be
the first statement in the constructor of the subclass.
super cannot be used in a static context: The super keyword cannot be used in a static context, such as in a static method
or a static variable initializer.
super is not required to call a superclass method: While it is possible to use the super keyword to call a method in the
parent class, it is not required. If a method is not overridden in the subclass, then calling it without the super keyword will invoke the
parent class’s implementation.
void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output
Maximum Speed: 120
final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
Usage 2: The other use of final with classes is to create an immutable class like the predefined String class. One can not make a
class immutable without making it final.
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// Compile-error! We can not override
System.out.println("Illegal!");
}
}
Ensuring immutability: When a variable or reference is marked as final, its value cannot be changed once it is assigned.
This helps ensure that data is immutable and cannot be accidentally or maliciously modified.
Improving performance: The use of the final can sometimes help improve performance, as the Java Virtual Machine (JVM)
can optimize code more effectively when it knows that certain values or references cannot be changed.
Making code easier to understand: By declaring variables, methods, or classes as final, developers can make their code
easier to understand and reason about. When a value or reference is marked as final, it is clear that it will not change, which can
simplify code analysis and debugging.
Promoting code reuse: By declaring methods as final, developers can prevent subclasses from overriding them. This can
help promote code reuse and reduce duplication, as subclasses must use the parent class’s implementation of the method.
Enhancing security: The use of final can help enhance security by preventing malicious code from modifying sensitive data
or behavior.
—--------
Object class and its methods:
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a
class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly
derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of the inheritance
hierarchy in any Java Program.
Using Object Class Methods
The Object class provides multiple methods which are as follows:
toString() method
hashCode() method
equals(Object obj) method
finalize() method
getClass() method
clone() method
wait(), notify() notifyAll() methods
1. toString() method
The toString() provides a String representation of an object and is used to convert an object to a String. The default
toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign
character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, it is defined as:
2. hashCode() method
It returns a hash value that is used to search objects in a collection. JVM(Java Virtual Machine) uses the hashcode
method while saving objects into hashing-related data structures like HashSet, HashMap, Hashtable, etc. The main advantage of
saving objects based on hash code is that searching becomes easy.
// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}
// Overriding hashCode()
@Override public int hashCode() { return roll_no; }
// Driver code
public static void main(String args[])
{
Student s = new Student();
Output :
Student@64
Student@64
Output:
5. finalize() method
This method is called just before an object is garbage collected. It is called the Garbage Collector on an object when the
garbage collector determines that there are no more references to the object. We should override finalize() method to dispose of
system resources, perform clean-up activities and minimize memory leaks. For example, before destroying the Servlet objects web
container, always called finalize method to perform clean-up activities of the session.
t = null;
System.out.println("end");
}
Output:
1510467688
finalize method called
end
6. clone() method
It returns a new object that is exactly the same as this object. For clone() method refer Clone().
The remaining three methods wait(), notify() notifyAll() are related to Concurrency. Refer to Inter-thread Communication in Java for
details.
—------------
Polymorphism:
The word ‘polymorphism’ means ‘having many forms’. In simple words, we can define Java Polymorphism as the ability of
a message to be displayed in more than one form. In this article, we will learn what is polymorphism and its type.
Real-life Illustration of Polymorphism in Java: A person can have different characteristics at the same time. Like a man at
the same time is a father, a husband, and an employee. So the same person possesses different behaviors in different situations.
This is called polymorphism.
Compile-time Polymorphism
Runtime Polymorphism
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.
Method Overloading
When there are multiple functions with the same name but different parameters then these functions are said to be overloaded.
Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments.
// Class 1
// Helper class
class Helper {
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
// Class 2
// Main class
class College {
// Main driver method
public static void main(String[] args)
{
// Calling method by passing
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
Output
8
34.65
2. Operator Overloading
It is a feature in C++ where the operators such as +, -, *, etc. can be given additional meanings when applied to
user-defined data types.
3. Template
it is a powerful feature in C++ that allows us to write generic functions and classes. A template is a blueprint for creating a
family of functions or classes.
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved
at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a
derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
// Class 1
// Helper class
class Parent {
// Print statement
System.out.println("parent class");
}
}
// Class 2
// Helper class
class subclass1 extends Parent {
// Method
void Print() { System.out.println("subclass1"); }
}
// Class 3
// Helper class
class subclass2 extends Parent {
// Method
void Print()
{
// Print statement
System.out.println("subclass2");
}
}
// Class 4
// Main class
class College {
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Output
subclass1
subclass2
Java abstract class is a class that can not be initiated by itself, it needs to be subclassed by another class to use its properties. An
abstract class is declared using the “abstract” keyword in its class definition.
In Java, the following some important observations about abstract classes are as follows:
data member
abstract method
method body (non-abstract method)
constructor
main() method.
Below is the implementation of the above topic:
void Learn(){
System.out.println("Preparing Right Now!");
}
}
class College {
public static void main(String[] args) {
Subject x=new IT();
x.syllabus();
x.Learn();
}
}
Output
Learning Subject
C , Java , C++
Preparing Right Now!
Abstract Method
The abstract Method is used for creating blueprints for classes or interfaces. Here methods are defined but these methods
don’t provide the implementation. Abstract Methods can only be implemented using subclasses or classes that implement the
interfaces.
These methods are sometimes referred to as subclass responsibility because they have no implementation specified in
the super-class. Thus, a subclass must override them to provide a method definition.
// Abstract Class
abstract class arithmetic_operation {
abstract void printInfo();
}
// Class add
class add extends arithmetic_operation {
// class add must override printInfo() method
// otherwise, compile-time
// exception will be thrown
void printInfo()
{
int a = 3;
int b = 4;
System.out.println(a + b);
}
}
// Class sub
class sub extends arithmetic_operation {
// class sub must override printInfo() method
// otherwise, compile-time
// exception will be thrown
void printInfo()
{
int c = 4;
int d = 5;
System.out.println(c - d);
}
}
// Driver Class
class abstraction {
// Main Function
public static void main(String args[])
{
arithmetic_operation n = new add();
n.printInfo();
arithmetic_operation y = new sub();
y.printInfo();
}
}
Output
7
-1
Unit - III
Interface Vs Abstract class:
Definition Cannot be instantiated; contains both Specifies a set of methods a class must
abstract (without implementation) and implement; methods are abstract by
concrete methods (with implementation) default.
Implementation Method Can have both implemented and Methods are abstract by default; Java 8,
abstract methods. can have default and static methods.
Inheritance class can inherit from only one abstract A class can implement multiple
class. interfaces.
Access Modifiers Methods and properties can have any Methods and properties are implicitly
access modifier (public, protected, public.
private).
Variables Can have member variables (final, Variables are implicitly public, static, and
non-final, static, non-static). final (constants).
Type of Methods Can have both abstract and concrete Can have only abstract methods (until
methods Java 7), and from Java 8, can have
default and static methods, and from
Java 9, can have private methods.
Implementing Interface:
The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface could only have abstract methods
(methods without a body) and public, static, and final variables by default. It is used to achieve abstraction and multiple inheritance
in Java. In other words, interfaces primarily define methods that other classes must implement. Java Interface also represents the
IS-A relationship.
In Java, the abstract keyword applies only to classes and methods, indicating that they cannot be instantiated directly and must be
implemented.
When we decide on a type of entity by its behavior and not via attribute we should define it as an interface.
Syntax for Java Interfaces
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface
are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an
interface must implement all the methods declared in the interface. To implement the interface, use the implements keyword.
The reason is, abstract classes may contain non-final variables, whereas variables in the interface are final, public, and static.
// A simple interface
interface Player
{
final int id = 10;
int move();
}
In class, you can instantiate variables and create an object. In an interface, you must initialize variables as they are final
but you can’t create an object.
A class can contain concrete (with implementation) methods The interface cannot contain concrete (with implementation)
methods.
The access specifiers used with classes are private, protected, In Interface only one specifier is used- Public.
and public.
import java.io.*;
// A simple interface
interface In1 {
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Output
Geek
10
// Interface 1
interface API {
// Default method
default void show()
{
// Print statement
System.out.println("Default API");
}
}
// Interface 2
// Extending the above interface
interface Interface1 extends API {
// Abstract method
void display();
}
// Interface 3
// Extending the above interface
interface Interface2 extends API {
// Abstract method
void print();
}
// Main class
// Implementation class code
class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class
// in main() method
TestClass d = new TestClass();
Output
Default API
Display from Interface1
Print from Interface2
Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class implements an interface that inherits
another interface, it must provide an implementation for all methods required by the interface inheritance chain.
interface Student
{
public void data();
}
class avi implements Student
{
public void data ()
{
String name="avinash";
int rollno=68;
System.out.println(name);
System.out.println(rollno);
}
}
public class inter_face
{
public static void main (String args [])
{
avi h= new avi();
h.data();
}
}
Output
avinash
68
—--------
Packages in java
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for:
Preventing naming conflicts. For example there can be two classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
Providing controlled access: protected and default have package level access control. A protected member is accessible by classes
in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same
package only.
Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and
use it in our program. A package is a container of a group of related classes where some of the classes are accessible are exposed
and others are kept for internal purpose. We can reuse existing classes from the packages as many time as we need it in our
program.
Package names and directory structure are closely related. For example if a package name is college.staff.cse, then there
are three directories, college, staffand cse such that cse is present in staff and staff is present inside college. Also, the directory
college is accessible through CLASSPATH variable, i.e., path of parent directory of college is present in CLASSPATH. The idea is
to make sure that classes are easy to locate.
Package naming conventions : Packages are named in reverse order of domain names, i.e., org.College.practice. For
example, in a college, the recommended convention is college.tech.cse, college.tech.ee, college.art.history, etc.
Adding a class to a Package : We can add more classes to a created package by using package name at the top of the
program and saving it in the package directory. We need a new java file to define a public class, otherwise we can add the new
class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are not imported by default, they
have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered as different
package for protected and default access specifiers.
Example :
import java.util.*;
util is a subpackage created inside java package.
First Statement is used to import Vector class from util package which is contained inside java.
Second statement imports all the classes from util package.
// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.package.Date;
Types of Packages:
Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Setting CLASSPATH: CLASSPATH can be set by any of the following ways:
CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment
Variables ? choose “System Variables” (for all the users) or “User Variables” (only the currently login user) ? choose “Edit” (if
CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the variable name ? Enter the required directories and JAR files
(separated by semicolons) as the value (e.g., “.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”). Take note that you need to
include the current working directory (denoted by ‘.’) in the CLASSPATH. To check the current setting of the CLASSPATH, issue the
following command:
> SET CLASSPATH
CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:
> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac
and java commands, for example,
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
Illustration of user-defined packages: Creating our first package: File name – ClassOne.java, ClassTwo.java
import package_name.ClassOne;
import package_one.ClassTwo;
Output:
Important points:
1. Using exception the main application logic can be separated out from the code which may cause some unusual
conditions.
2. When calling method encounters some error then the exception can be thrown. This avoids crashing of the entire
application abruptly.
3. The working code and the error handling code can be separated out due to exception handling mechanism. Using
exception handling, various types of errors in the source code can be grouped together.
4. Due to exception handling mechanism, the errors can be propagated up the method call stack i.e. problems occurring at
the lower level can be handled by the higher up methods.
Exception Hierarchy
All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. One branch
is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception. Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with
the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Types of exceptions:
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own
exceptions.
Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error
situations. Below is the list of important built-in exceptions in Java.
Output
Can't divide a number by 0
B. NullPointer Exception
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
Output
NullPointerException..
C. StringIndexOutOfBound Exception
Output
StringIndexOutOfBoundsException
D. FileNotFound Exception
Output:
E. NumberFormat Exception
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output
Number format exception
F. ArrayIndexOutOfBounds Exception
Output
Array Index is Out Of Bounds
G. IO Exception
scan.close();
}
}
Output:
Hello Geek!
Exception Output: null
H. NoSuchMethod Exception
exampleleSet.iterator().next();
//accessing Set
exampleTable.elements().nextElement();
//accessing Hashtable
I. IllegalArgumentException: This program, checks whether the person is eligible for voting or not. If the age is greater
than or equal to 18 then it will not throw any error. If the age is less than 18 then it will throw an error with the error statement.
Also, we can specify “throw new IllegalArgumentException()” without the error message. We can also specify
Integer.toString(variable_name) inside the IllegalArgumentException() and It will print the argument name which is not satisfied the
given condition.
import java.io.*;
class College {
public static void print(int a)
{
if(a>=18){
System.out.println("Eligible for Voting");
}
else{
}
public static void main(String[] args) {
College.print(14);
}
}
Output :
J. IllegalStateException: This program, displays the addition of numbers only for Positive integers. If both the numbers
are positive then only it will call the print method to print the result otherwise it will throw the IllegalStateException with an error
statement. Here, the method is not accessible for non-positive integers.
Also, we can specify the “throw new IllegalStateException()” without the error statement.
import java.io.*;
class College {
public static void print(int a,int b)
{
System.out.println("Addition of Positive Integers :"+(a+b));
}
Output :
Exception in thread "main" java.lang.IllegalStateException: Either one or two numbers are not Positive Integer
at College.main(File.java:20)
k. ClassNotFound Exception :
Output
java.lang.ClassNotFoundException: Class1
Class Not Found...
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, the user can also
create exceptions which are called ‘user-defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
The user should create an exception class as a subclass of the Exception class. Since all the exceptions are subclasses of the
Exception class, the user should also make his class a subclass of it. This is done as:
class MyException extends Exception
We can write a default constructor in his own exception class.
MyException(){}
We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call the superclass(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
To raise an exception of a user-defined type, we need to create an object to his exception class and throw it using the throw clause,
as:
MyException me = new MyException(“Exception details”);
throw me;
The following program illustrates how to create your own exception class MyException.
Details of account numbers, customer names, and balance amounts are taken in the form of three arrays.
In main() method, the details are displayed using a for-loop. At this time, a check is done if in any account the balance
amount is less than the minimum balance amount to be apt in the account.
If it is so, then MyException is raised and a message is displayed “Balance amount is less”.
// default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");
catch (MyException e) {
e.printStackTrace();
}
}
}
Runtime Error
Output:
Checked exceptions
Unchecked exceptions
Checked Exceptions in Java
These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the
method must either handle the exception or it must specify the exception using the throws keyword. Checked exceptions can be
fully checked or partially checked.
Fully Checked Exception: A checked exception where all its child classes are also checked (e.g., IOException,
InterruptedException).
Partially Checked Exception: A checked exception where some of its child classes are unchecked (e.g.,
Exception).
Checked exceptions represent invalid conditions in areas outside the immediate control of the program (like memory, network, file
system, etc.). Any checked exception is a subclass of Exception. Unlike unchecked exceptions, checked exceptions must be either
caught by the caller or listed as part of the method signature using the throws keyword.
// Main class
class College {
Output
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile
because ArithmeticException is an unchecked exception.
// Main class
class College {
Output
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
3. throw in Java
The throw keyword is used to transfer control from the try block to the catch block.
Output
Caught inside help().
Caught in main error name given below:
java.lang.NullPointerException: error_unknown
4. throws in Java
The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can
throw to the caller and does not handle itself.
Output
Inside fun().
caught in main.
5. finally in Java
It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an
exception has occurred or not ) when there are multiple catch blocks.
An example of an exception generated by the system is given below:
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
finally {
System.out.println("I am in final block");
}
}
}
Output
Exception caught:Division by zero
I am in final block
Rethrowing Exceptions:
When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception
objects).
While re-throwing exceptions you can throw the same exception as it is without adjusting it as −
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArithmeticException e) {
throw e;
}
Or, wrap it within a new exception and throw it. When you wrap a cached exception within another exception and throw it, it is
known as exception chaining or, exception wrapping, by doing this you can adjust your exception, throwing a higher level of
exception maintaining the abstraction.
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}
Example
In the following Java example our code in demoMethod() might throw ArrayIndexOutOfBoundsException an
ArithmeticException. We are catching these two exceptions in two different catch blocks.
In the catch blocks, we are re-throwing both exceptions one by wrapping within the higher exceptions and the other one directly.
import java.util.Arrays;
import java.util.Scanner;
public class RethrowExample {
public void demoMethod() {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}
catch(ArithmeticException e) {
throw e;
}
}
public static void main(String [] args) {
new RethrowExample().demoMethod();
}
}
Output1
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
4
Exception in thread "main" java.lang.ArithmeticException: / by zero
at myPackage.RethrowExample.demoMethod(RethrowExample.java:16)
at myPackage.RethrowExample.main(RethrowExample.java:25)
Output2
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
at myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
at myPackage.RethrowExample.main(RethrowExample.java:23)
—-----------------
Unit - IV
Multithreading
Multiprocessing uses multiple CPUs to run many processes at a time while multithreading creates multiple threads within a
single process to get faster and more efficient task execution. Both Multiprocessing and Multithreading are used to increase the
computing power of a system in different ways. In this article, we are going to
discuss the difference between multiprocessing and multithreading in detail.
What is Multiprocessing?
Multiprocessing is a system that has more than one or two processors. In
Multiprocessing, CPUs are added to increase the computing speed of the
system. Because of Multiprocessing, There are many processes are executed
simultaneously. Explore more about similar topics. Multiprocessing is classified into two categories:
1. Symmetric Multiprocessing
2. Asymmetric Multiprocessing
Advantages
Increases computing power by utilizing multiple processors.
Suitable for tasks that require heavy computational power.
Disadvantages
Process creation is time-consuming.
Each process has its own address space, which can lead to higher memory usage.
What is Multithreading?
Multithreading is a system in which multiple threads are created of a process for increasing the computing speed of the
system. In multithreading, many threads of a process are executed simultaneously and process creation in multithreading
is done according to economical.
Advantages
More efficient than multiprocessing for tasks within a single process.
Threads share a common address space, which is memory-efficient.
Disadvantages
Not classified into categories like multiprocessing.
Thread creation is economical but can lead to synchronization
issues.
Multiprocessing are classified into Symmetric and Asymmetric. While Multithreading is not classified in any categories.
In Multiprocessing, Process creation is a time-consuming process. While in Multithreading, process creation is according to economical.
In Multiprocessing, every process owned a separate address space. While in Multithreading, a common address space is shared by all the threads.
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any
instant:
New State
Runnable State
Blocked State
Waiting State
Timed Waiting State
Terminated State
New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run when the
thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t started to execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might actually be
running or it might be ready to run at any instant of time. It is the responsibility of the thread scheduler to give the thread, time to
run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every thread runs for a short while
and then pauses and relinquishes the CPU to another thread so that other threads can get a chance to run. When this happens, all
such threads that are ready to run, waiting for the CPU and the currently running thread lie in a runnable state.
Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is acquired by the
other thread. The thread will move from the blocked state to runnable state when it acquires the lock.
Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will move to the
runnable state when other thread will notify or that thread will be terminated.
Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter. A thread lies in
this state until the timeout is completed or until a notification is received. For example, when a thread calls sleep or a conditional
wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following reasons:
Because it exits normally. This happens when the code of the thread has been entirely executed by the program.
Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled exception.
Implementing the Thread States in Java
In Java, to get the current state of the thread, use Thread.getState() method to get the current state of the thread. Java provides
java.lang.Thread.State class that defines the ENUM constants for the state of a thread, as a summary of which is given below:
1. New
Thread state for a thread that has not yet started.
Thread.sleep
Object.wait with timeout
Thread.join with timeout
LockSupport.parkNanos
LockSupport.parkUntil
public static final Thread.State TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
System.out.println(
"State of thread1 while it called join() method on thread2 -"
+ Test.thread1.getState());
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"State of thread2 when it has finished it's execution - "
+ thread2.getState());
}
}
Output :
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it - TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED
Create a Thread
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread
shares process resources. The main thread of Java is the thread that is started when the program starts. The slave thread is
created as a result of the main thread. This is the last thread to complete execution.
Thread Class:
The Thread class provides constructors and methods for creating and operating on threads. The thread extends the
Object and implements the Runnable interface.
Any class with instances that are intended to be executed by a thread should implement the Runnable interface. The Runnable
interface has only one method, which is called run().
The common mistake is starting a thread using run() instead of start() method.
import java.io.*;
class College extends Thread {
public void run()
{
System.out.print("Welcome to College.");
}
public static void main(String[] args)
{
College g = new Colege(); // creating thread
g.start(); // starting thread
}
}
Output :
Welcome to College
import java.io.*;
class College implements Runnable {
public static void main(String args[])
{
// create an object of Runnable target
College College = new College();
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method
on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting
state, calling the interrupt() method performs normal behavior and doesn’t interrupt the thread but sets the interrupt flag to true.
interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the
execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with
the help of the interrupt() method of Thread class.
Example: Suppose there are two threads and If one of the threads is blocked in an invocation of the wait(), wait(long), or wait(long,
int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then
its interrupt status will be cleared and it will receive an InterruptedException, which gives the chance to another thread to execute
the corresponding run() method of another thread which results into high performance and reduces the waiting time of the threads.
class Test {
public static void main(String[] args)
throws InterruptedException
{
MyClass thread = new MyClass();
thread.start();
Case 3: Interrupting a thread that works normally: In the program, there is no exception occurred during the execution of the thread.
Here, interrupt only sets the interrupted flag to true, which can be used by Java programmers later.
Thread Priorities
As we already know java being completely object-oriented works within a multithreading environment in which thread
scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has
some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be given by the programmer
explicitly.
Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every
object is having priority here which is represented by numbers ranging from 1 to 10.
We will use currentThread() method to get the name of the current thread. User can also use setName() method if he/she
wants to make names of thread as per choice for understanding purposes.
getName() method will be used to get the name of the thread.
The accepted value of priority for a thread is in the range of 1 to 10.
Let us do discuss how to get and set priority of a thread in java.
public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread to
the value newPriority. This method throws IllegalArgumentException if value of parameter newPriority goes
beyond minimum(1) and maximum(10) limit.
Example
// Main class
class ThreadDemo extends Thread {
// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in main()
public void run()
{
// Print statement
System.out.println("Inside run method");
}
// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "+ t1.getPriority());
// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "+ t2.getPriority());
// Thread 3
System.out.println("t3 thread priority : "+ t3.getPriority());
// 2
System.out.println("t1 thread priority : "+ t1.getPriority());
// 5
System.out.println("t2 thread priority : "+ t2.getPriority());
// 8
System.out.println("t3 thread priority : "+ t3.getPriority());
// Main thread
Output :
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Output explanation:
Thread with the highest priority will get an execution chance prior to other threads. Suppose there are 3 threads t1, t2, and
t3 with priorities 4, 6, and 1. So, thread t2 will execute first based on maximum priority 6 after that t1 will execute and then t3.
The default priority for the main thread is always 5, it can be changed later. The default priority for all other threads depends on the
priority of the parent thread.
Synchronizing Threads
Java provides a way of creating threads and synchronizing their tasks using synchronized blocks.
A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object
and can only have one thread executed inside them at a time. All other threads attempting to enter the synchronized block are
blocked until the thread inside the synchronized block exits the block. If you want to master concurrency and understand how to
avoid common pitfalls, the Java Programming Course offers in-depth coverage of synchronization with practical coding exercises.
Note: Synchronized blocks in Java are marked with the synchronized keyword.
Types of Synchronization
There are two synchronizations in Java mentioned below:
Process Synchronization
Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of multiple processes. It ensures that the shared
resources are safe and in order.
Mutual Exclusive
Cooperation (Inter-thread communication in Java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. There are three types of Mutual
Exclusive mentioned below:
Synchronized method.
Synchronized block.
Static synchronization.
Example of Synchronization
Below is the implementation of the Java Synchronization:
import java.io.*;
import java.util.*;
// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
// Start two threads of ThreadedSend type
S1.start();
S2.start();
Explanation
In the above example, we choose to synchronize the Sender object inside the run() method of the ThreadedSend class.
Alternatively, we could define the whole send() block as synchronized, producing the same result.
Example of the synchronized method by using an anonymous class
class Test {
synchronized void test_function(int n)
{
// synchronized method
for (int i = 1; i <= 3; i++) {
System.out.println(n + i);
try {
Thread.sleep(500);
}
catch (Exception e) {
System.out.println(e);
}
}
}
}
// Driver Class
public class GFG {
// Main function
public static void main(String args[])
{
// only one object
final Test obj = new Test();
a.start();
b.start();
}
}
Output :
16
17
18
31
32
33
Inter-thread Communication
Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical section and another
thread is allowed to enter (or lock) in the same critical section to be executed.
Java uses three methods, namely, wait(), notify(), and notifyAll(). All these methods belong to object class as final so that
all classes have them. They must be used within a synchronized block only.
wait():
It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls
notify():
It wakes up one single thread called wait() on the same object. It should be noted that calling notify() does not give up a
lock on a resource.
notifyAll():
It wakes up all the threads called wait() on the same object.
Example:
A simple Java program to demonstrate the three methods. Please note that this program might only run in offline IDEs as it
contains taking input at several points.
import java.util.LinkedList;
import java.util.Queue;
// Producer task
private static final Runnable producer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
// Wait if the queue is full
while (queue.size() == CAPACITY) {
try {
System.out.println("Queue is at max capacity");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Add item to the queue
queue.add(10);
System.out.println("Added 10 to the queue");
queue.notifyAll(); // Notify all waiting consumers
try {
Thread.sleep(2000); // Simulate some delay in production
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
// Consumer task
private static final Runnable consumer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
// Wait if the queue is empty
while (queue.isEmpty()) {
try {
System.out.println("Queue is empty, waiting");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Remove item from the queue
System.out.println("Removed " + queue.remove() + " from the queue");
queue.notifyAll(); // Notify all waiting producers
try {
Thread.sleep(2000); // Simulate some delay in consumption
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
This example effectively demonstrates inter-thread communication in Java using a typical producer-consumer problem,
showcasing the practical use of wait(), notifyAll(), and synchronization.
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O
Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package
provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text.
Input Stream: reads data from the source.
Output Stream: writes data to a destination.
Names of character streams typically end with Reader/Writer and names of byte streams end with
InputStream/OutputStream
The streams used in example codes are unbuffered streams and less efficient. We typically use them with buffered
readers/writers for efficiency. We will soon be discussing use BufferedReader/BufferedWriter (for character stream) and
BufferedInputStream/BufferedOutputStream (for byte stream) classes.
It is always recommended to close the stream if it is no longer in use. This ensures that the streams won’t be affected if
any error occurs.
The above codes may not run in online compilers as files may not exist.
Character Stream
In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data
character by character. For example, FileReader and FileWriter are character streams used to read from the source and write to the
destination.
// Main class
public class GFG {
int temp;
// Main class
public class GFG {
if (targetStream != null)
targetStream.close();
}
}
}
Output:
In Java, there are four different ways to read input from the user in the command line environment(console).
Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we use split().
Reading input from the console is a common task in Java applications. If you want to explore more ways to handle user
input and optimize your code for various scenarios, the Java Programming Course provides hands-on lessons with practical
examples.
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens.
The reading methods are not synchronized.
class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string " + s);
int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
Input:
GeeksforGeeks
12
3.4
Output:
You entered string GeeksforGeeks
You entered integer 12
You entered float 3.4
Advantages:
Output:
You entered string GeeksforGeeks
javac GFG1.java
java Main Hello World
Output:
The command line arguments are:
Hello
World
Definition:
DataInputStream is a Java class that implements data input operations. It allows applications to read primitive data types
and strings from an input stream in a machine-independent way. It achieves this by wrapping an existing input stream and providing
methods to read various primitive data types and strings from the underlying input source.
Remember that DataInputStream reads data in a binary format, so it’s important to ensure that the data being read was
written using the correct methods in DataOutputStream or a compatible source to avoid data corruption or misinterpretation.
Code Implementation:
// Reading integers
System.out.print("Enter an integer: ");
int inputInt = Integer.parseInt(reader.readLine());
// Reading strings
System.out.print("Enter a string: ");
String inputString = reader.readLine();
System.out.println("You entered integer: " + inputInt);
System.out.println("You entered string: " + inputString);
}
}
Input:
Enter an integer: 10
Enter a string: GeeksForGeeks
Output:
You entered integer: 10
You entered string :GeeksForGeeks
Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array,
character and strings. A buffer size needs to be specified, if not it takes Default value.
An output is immediately set to the underlying character or byte stream by the Writer.
Class Declaration
Constructors
BufferedWriter(Writer out):
Creates a buffered character-output stream that uses a default-sized output buffer.
BufferedWriter(Writer out, int size):
Creates a new buffered character-output stream that uses an output buffer of the given size.
Methods:
write() : java.io.BufferedWriter.write(int arg) writes a single character that is specified by an integer argument.
newLine() : java.io.BufferedWriter.newLine() breaks/separates line.
flush() : java.io.BufferedWriter.flush() flushes character from write buffer.
close() : java.io.BufferedWriter.close() flushes character from write buffer and then close it.
Implementation :
geekwrite.write(69); // Printing E
geekwrite.newLine(); // For next line
geekwrite.write(49); // Printing 1
}
}
Output :
Buffered Writer start writing :)
Written successfully
In Java, OutputStreamWriter class connects character streams to byte streams. It encodes Characters into bytes using a specified
charset.
// Driver Class
public class NewClass {
// Main Function
public static void main(String[] args)
{
char[] geek = { 'G', 'E', 'E', 'K', 'S' };
try {
// Creation of new OutputStreamWriter
OutputStream g
= new FileOutputStream("test.txt");
OutputStreamWriter geeks_out1
= new OutputStreamWriter(g);
File Class :
Java File class is Java’s representation of a file or directory pathname. Because file and directory names have different
formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working
with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several
common attributes of files and directories.
pathSeperator String the character or string used to separate individual paths in a list of file system paths.
pathSeperatorChar Char the character used to separate individual paths in a list of file system paths.
Tests whether the application can execute the file denoted by this abstract
1. canExecute() boolean
pathname.
Tests whether the application can read the file denoted by this abstract
2. canRead() boolean
pathname.
Tests whether the application can modify the file denoted by this abstract
3. canWrite() boolean
pathname.
compareTo(File
4. Compares two abstract pathnames lexicographically. int
pathname)
5. createNewFile() Atomically creates a new, empty file named by this abstract pathname. boolean
createTempFile(String
6. Creates an empty file in the default temporary-file directory. File
prefix, String suffix)
7. delete() Deletes the file or directory denoted by this abstract pathname. boolean
8. equals(Object obj) Tests this abstract pathname for equality with the given object. boolean
9. exists() Tests whether the file or directory denoted by this abstract pathname exists. boolean
10. getAbsolutePath() Returns the absolute pathname string of this abstract pathname. String
11. list() Returns an array of strings naming the files and directories in the directory. String[]
12. getFreeSpace() Returns the number of unallocated bytes in the partition. long
13. getName() Returns the name of the file or directory denoted by this abstract pathname. String
14. getParent() Returns the pathname string of this abstract pathname’s parent. String
15. getParentFile() Returns the abstract pathname of this abstract pathname’s parent. File
16. getPath() Converts this abstract pathname into a pathname string. String
17. setReadOnly() Marks the file or directory named so that only read operations are allowed. boolean
18. isDirectory() Tests whether the file denoted by this pathname is a directory. boolean
19. isFile() Tests whether the file denoted by this abstract pathname is a normal file. boolean
20. isHidden() Tests whether the file named by this abstract pathname is a hidden file. boolean
21. length() Returns the length of the file denoted by this abstract pathname. long
22. listFiles() Returns an array of abstract pathnames denoting the files in the directory. File[]
23. mkdir() Creates the directory named by this abstract pathname. boolean
24. renameTo(File dest) Renames the file denoted by this abstract pathname. boolean
setExecutable(boolean
25. A convenience method to set the owner’s execute permission. boolean
executable)
setReadable(boolean
26. A convenience method to set the owner’s read permission. boolean
readable)
setReadable(boolean
27. readable, boolean Sets the owner’s or everybody’s read permission. boolean
ownerOnly)
setWritable(boolean
28. A convenience method to set the owner’s write permission. boolean
writable)
29. toString() Returns the pathname string of this abstract pathname. String
30. toURI() Constructs a file URI that represents this abstract pathname. URI
import java.io.File;
if (f.exists()) {
System.out.println("Is writable:"
+ f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:"
+ f.isDirectory());
System.out.println("File Size in bytes "
+ f.length());
}
}
}
Output
Here we will accept a directory name from the keyboard and then display all the contents of the directory. For this purpose, list()
method can be used as:
String arr[]=f.list();
In the preceding statement, the list() method causes all the directory entries copied into the array arr[]. Then pass these array
elements arr[i] to the File object and test them to know if they represent a file or directory.
System.out.println("Enter dirpath:");
String dirpath = br.readLine();
System.out.println("Enter the dirname");
String dname = br.readLine();
// if directory exists,then
if (f.exists()) {
// get the contents into arr[]
// now arr[i] represent either a File or
// Directory
String arr[] = f.list();
Enter dirpath:
C:\Users\akki\IdeaProjects\
Enter the dirname
codewriting
.idea
: is a directory
an1.txt
: is a file
codewriting.iml
: is a file
file.txt
: is a file
out
: is a directory
src
: is a directory
text
: is a file
No of entries in this directory 7
Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is
recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information
as these are Byte stream classes.
FileWriter
FileWriter is useful to create a file writing characters into it.
FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
FileWriter creates the output file if it is not present already.
Constructors:
Reading and writing take place character by character, which increases the number of I/O operations and affects the
performance of the system.BufferedWriter can be used along with FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter
System.out.println("Writing successful");
//close the file
fw.close();
}
}
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
Constructors:
public int read () throws IOException – Reads a single character. This method will block until a character is available, an I/O error
occurs, or the end of the stream is reached.
public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until some input is
available, an I/O error occurs, or the end of the stream is reached.
public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an array. This method will
block until some input is available, an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
Important Points:
It provides methods to read text and password. If you read password using Console class, it will not be displayed to the
user.The java.io.Console class is attached with system console internally.
Important Methods:
writer : Retrieves the unique PrintWriter object associated with this console.
reader : Retrieves the unique Reader object associated with this console.
format : Writes a formatted string to this console’s output stream using the specified format string and arguments.
printf : A convenience method to write a formatted string to this console’s output stream using the specified format string
and arguments.
readLine : Provides a formatted prompt, then reads a single line of text from the console.
readLine : Reads a single line of text from the console.
readPassword: Provides a formatted prompt, then reads a password or passphrase from the console with echoing
disabled.
readPassword : Reads a password or passphrase from the console with echoing disabled.
flush : Flushes the console and forces any buffered output to be written immediately .
// Java Program to demonstrate Console Methods
import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
Serialization:
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process
where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.
Serialization and deserialization are crucial for saving and restoring the state of objects in Java. To explore more advanced
use cases and learn best practices, the Java Programming Course provides detailed lessons on object serialization with practical
examples.
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a
different platform. To make a Java object serializable we implement the java.io.Serializable interface. The ObjectOutputStream
class contains writeObject() method for serializing an Object.
// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}
class Test
{
public static void main(String[] args)
{
Demo object = new Demo(1, "geeksforgeeks");
String filename = "file.ser";
// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
in.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Output :
Components of AWT are heavy weighted. The components of Java Swing are lightweight.
Execution Time is more than Swing. Execution Time is less than AWT.
AWT components require java.awt package. Swing components requires javax.swing package.
// Main class
class GFG {
class button {
button()
{
Frame f = new Frame();
// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);
// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);
// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
// Driver Class
class Lan {
// Main Function
Lan()
{
// Frame Created
Frame f = new Frame();
// CheckBox created
Checkbox c2 = new Checkbox("Hindi");
c2.setBounds(100, 150, 50, 50);
f.add(c2);
// CheckBox created
Checkbox c3 = new Checkbox("English");
c3.setBounds(100, 200, 80, 50);
f.add(c3);
// CheckBox created
Checkbox c4 = new Checkbox("marathi");
c4.setBounds(100, 250, 80, 50);
f.add(c4);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
Class Description
A Component is the Abstract base class for about the non-menu user-interface controls of Java SWING. Components are
Component
representing an object with a graphical representation.
A JComponent is a base class for all swing UI Components In order to use a swing component that inherits from
JComponent
JComponent, the component must be in a containment hierarchy whose root is a top-level Java Swing container.
JColorChoose
A JColorChooser provides a pane of controls designed to allow the user to manipulate and select a color.
r
JCheckBox A JCheckBox is a graphical (GUI) component that can be in either an on-(true) or off-(false) state.
JRadioButton The JRadioButton class is a graphical (GUI) component that can be in either an on-(true) or off-(false) state. in the group
JList A JList component represents the user with the scrolling list of text items.
JComboBox A JComboBox component is Presents the User with a show up Menu of choices.
JTextField A JTextField object is a text component that will allow for the editing of a single line of text.
JPasswordFie
A JPasswordField object it is a text component specialized for password entry.
ld
JTextArea A JTextArea object is a text component that allows for the editing of multiple lines of text.
Imagelcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images
JScrollbar A JScrollbar control represents a scroll bar component in order to enable users to Select from range values.
JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or Something.
JFileChooser A JFileChooser it Controls represents a dialog window from which the user can select a file.
JProgressBar As the task progresses towards completion, the progress bar displays the tasks percentage on its completion.
JSlider A JSlider this class is letting the user graphically (GUI) select by using a value by sliding a knob within a bounded interval.
A JSpinner this class is a single line input where the field that lets the user select by using a number or an object value from
JSpinner
an ordered sequence.
MVC Architecture:
The Model View Controller (MVC) design pattern specifies that an application consists of a data model, presentation
information, and control information. The pattern requires that each of these be separated into different objects.
The MVC pattern separates the concerns of an application into three distinct components, each responsible for a specific
aspect of the application’s functionality.
This separation of concerns makes the application easier to maintain and extend, as changes to one component do not
require changes to the other components.
To explore MVC further and learn how to implement it in various frameworks, the System Design Course provides a
thorough overview of the MVC pattern and its applications.
Components of the MVC Design Pattern :
1. Model
The Model component in the MVC (Model-View-Controller) design pattern demonstrates the data and business logic of an
application. It is responsible for managing the application’s data, processing business rules, and responding to requests for
information from other components, such as the View and the Controller.
2. View
Displays the data from the Model to the user and sends user inputs to the Controller. It is passive and does not directly interact with
the Model. Instead, it receives data from the Model and sends user inputs to the Controller for processing.
3. Controller
Controller acts as an intermediary between the Model and the View. It handles user input and updates the Model accordingly and
updates the View to reflect changes in the Model. It contains application logic, such as input validation and data transformation.
User Interaction with View: The user interacts with the View, such as clicking a button or entering text into a form.
View Receives User Input: The View receives the user input and forwards it to the Controller.
Controller Processes User Input: The Controller receives the user input from the View. It interprets the input, performs any
necessary operations (such as updating the Model), and decides how to respond.
Controller Updates Model: The Controller updates the Model based on the user input or application logic.
Model Notifies View of Changes: If the Model changes, it notifies the View.
View Requests Data from Model: The View requests data from the Model to update its display.
Controller Updates View: The Controller updates the View based on the changes in the Model or in response to user input.
View Renders Updated UI: The View renders the updated UI based on the changes made by the Controller.
Example of the MVC Design Pattern
Below is the code of above problem statement using MVC Design Pattern:
Let’s break down into the component wise code:
class Student {
private String rollNo;
private String name;
class StudentView {
public void printStudentDetails(String studentName, String studentRollNo) {
System.out.println("Student:");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
class StudentController {
private Student model;
private StudentView view;
controller.updateView();
controller.setStudentName("Science");
controller.updateView();
}
private static Student retriveStudentFromDatabase() {
Student student = new Student();
student.setName("Computer");
student.setRollNo("15UCS157");
return student;
}
}
Output :
Student:
Name:Computer
Roll No: 000001
Student:
Name: Science
Roll No: 000001
Containers: AWT provides containers like panels, frames, and dialogues to organize and group components in the Application.
Types of Containers in Java AWT
There are four types of containers in Java AWT:
Window: Window is a top-level container that represents a graphical window or dialog box. The Window class extends the
Container class, which means it can contain other components, such as buttons, labels, and text fields.
Panel: Panel is a container class in Java. It is a lightweight container that can be used for grouping other components
together within a window or a frame.
Frame: The Frame is the container that contains the title bar and border and can have menu bars.
Dialog: A dialog box is a temporary window an application creates to retrieve user input.
FlowLayout
FlowLayout is used to arrange components in a sequence one after the other. The default layout of applet and panel is FlowLayout.
Constructors :
FlowLayout(): It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels.
FlowLayout(int align) : It will Construct a new FlowLayout with given alignment.The horizontal and vertical gap will be 5
pixels.
FlowLayout(int align, int HorizontalGap, int VerticalGap ): It will Construct a new FlowLayout with given alignment, the
given horizontal and vertical gap between the components.
JLabel(String text): It will create a JLabel instance with the specified text.
setTitle(String Text): This Method is used to set Title of JFrame. The title you want to set is passed as a string.
getAlignment(): Returns the alignment for this layout.
setAlignment(int align): used to set the alignment for this layout.
removeLayoutComponent(Component comp): Used to remove the component passed as argument from the layout.
Below programs will illustrate the Example of FlowLayout in java.
Program 1: The following program illustrates the use of FlowLayout by arranging several JLabel components in a JFrame, whose
instance class is named as “Example”. We create 5 JLabel components named “l1”, “l2″… “l5” and then add them to the JFrame by
the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.
The layout is set by the method setLayout();
class MainFrame {
// Driver code
public static void main(String[] args)
{
// Creating Object of Example class.
Example f = new Example();
Border Layout :
BorderLayout is the default layout for the window objects such as JFrame, JWindow, JDialog, JInternalFrame etc.
BorderLayout arranges the components in the five regions. Four sides are referred to as north, south, east, and west. The middle
part is called the center. Each region can contain only one component and is identified by a corresponding constant as NORTH,
SOUTH, EAST, WEST, and CENTER.
Constructors:
BorderLayout(): It will construct a new borderlayout with no gaps between the components.
BorderLayout(int, int): It will constructs a border layout with the specified gaps between the components.
Commonly Used Methods:
toString(): Returns a string which is the representation of the state of border layout.
getLayoutAlignmentX(Container parent): Returns the layout alignment along the X-axis.
getLayoutAlignmentY(Container parent): It will return the layout alignment along the Y-axis.
removeLayoutComponent(Component comp): This method is used to remove the specified component from the
borderlayout.
getVgap(): Return the vertical gap between the components.
getHgap(): Returns the Horizontal gap between the components.
setHgap(int hgap): It is used to set the horizontal gap between the components.
setVgap(int vgap): It is used to set the vertical gap between the components.
Below Programs will illustrate the BorderLayout class:
BoderLayoutDemo()
{
class MainFrame {
// Driver code
public static void main(String[] args)
{
Grid Layout :
GridLayout class represents a layout manager with a specified number of rows and columns in a rectangular grid. The
GridLayout container is divided into an equal-sized of rectangles, and one of the components is placed in each rectangle. Every
rectangle cell has the same size therefore, they contain a component, which fills the entire cell. When the user changes or adjusts
the size of the container, the size of each rectangles changes accordingly.
GridLayout(): It Creates a grid layout with a default of one column per component, in a single row.
GridLayout(int rw, int cl): It creates a grid layout with the specified number of rows and columns.
GridLayout(int rw, int cl, int hgap, int vgap): It creates a grid layout with the specified number of rows and columns with
horizontal and vertical gap.
Commonly Used Methods:
addLayoutComponent(String str, Component cmp): Adds the specified component with the specified name to the layout.
setColumns(int cl): Sets the number of columns in this layout to the specified value.
setHgap(int hgap): Sets the horizontal gap between components to the specified value.
setRows(int rw): Sets the number of rows in this layout to the specified value.
setVgap(int vgap): Sets the vertical gap between components to the specified value.
layoutContainer(Container pr): Lays out the specified container using this layout.
toString(): Returns the string representation of this grid layout’s values.
Below programs illustrate the GridLayout class:
GridLayoutDemo() {
// Initialization of object
// "one" of JLabel class.
one = new JLabel("NAME");
// Initialization of object
// "tname" of JTextField class.
tname = new JTextField(20);
// Initialization of object
// "two" of JLabel class.
two = new JLabel("CODE");
// Initialization of object
// "tcode" of JTextField class.
tcode = new JTextField(20);
// Initialization of object
// "three" of JLabel class.
three = new JLabel("DESIGNATION");
// Initialization of object
// "tdesig" of JTextField class.
tdesig = new JTextField(20);
// Initialization of object
// "four" of JLabel class.
four = new JLabel("SALARY");
// Initialization of object
// "tsalary" of JTextField class.
tsalary = new JTextField(20);
// Initialization of object
// "buttonsave" of JButton class.
buttonSave = new JButton("SAVE");
// Initialization of object
// "buttonexit" of JButton class.
buttonExit = new JButton("EXIT");
// Main Method
public static void main(String args[])
{
Card Layout :
The CardLayout class manages the components in such a way that only one component is visible at a time. It treats each
component as a card in the container. Only one card is visible at a time, and the container acts as a stack of cards. The first
component added to a CardLayout object is the visible component when the container is first displayed.
Constructors:
CardLayout(): It is used to create a new card layout with gaps of size is zero.
CardLayout(int horizontalgap, int verticalgap): It is used to create a new CardLayout class with the specified
horizontal and vertical gaps.
Commonly Used Methods:
// Declaration of objects
// of CardLayout class.
private CardLayout cl;
public CardLayoutDemo()
{
// Initialization of object
// "jp1" of JPanel class.
JPanel jp1 = new JPanel();
// Initialization of object
// "jp2" of CardLayout class.
JPanel jp2 = new JPanel();
// Initialization of object
// "jp3" of CardLayout class.
JPanel jp3 = new JPanel();
// Initialization of object
// "jp4" of CardLayout class.
JPanel jp4 = new JPanel();
// Initialization of object
// "jl1" of JLabel class.
JLabel jl1 = new JLabel("Card1");
// Initialization of object
// "jl2" of JLabel class.
JLabel jl2 = new JLabel("Card2");
// Initialization of object
// "jl3" of JLabel class.
JLabel jl3 = new JLabel("Card3");
// Initialization of object
// "jl4" of JLabel class.
JLabel jl4 = new JLabel("Card4");
// Initialization of object
// "firstbtn" of JButton class.
JButton firstBtn = new JButton("First");
// Initialization of object
// "nextbtn" of JButton class.
JButton nextBtn = new JButton("Next");
// Initialization of object
// "previousbtn" of JButton class.
JButton previousBtn = new JButton("Previous");
// Initialization of object
// "lastbtn" of JButton class.
JButton lastBtn = new JButton("Last");
// value of currentcard is 1
currentCard = 1;
}
});
// value of currentcard is 4
currentCard = 4;
}
});
// if condition apply
if (currentCard < 4)
{
// Main Method
public static void main(String[] args)
{
GridBagLayout :
GridBagLayout class is a flexible layout manager. It is used to aligns the components horizontally, vertically, or along their
baseline. It doesn’t require the components of the same size. Each GridBagLayout object manages a rectangular grid of cells,
dynamic with each component occupying one or more cells, called its display area. GridBagLayout components are associated with
the instance of GridBagConstraints. These constraints are used to define the component’s display area and their positions. In
addition to its constraints object, the GridBagLayout also considers each component’s minimum and preferred sizes in order to
determine a component’s size. GridBagLayout components are also arranged in the rectangular grid but can have different sizes
and can occupy the multiple rows or columns.
Constructor:
// if condition
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
// if condition
if (shouldFill) {
// Initialization of object
// "button" of JButton class.
button = new JButton("Button 1");
// if condition
if (shouldWeightX) {
c.weightx = 0.5;
}
// column 0
c.gridx = 0;
// row 0
c.gridy = 0;
// Initialization of object
// "button" of JButton class.
button = new JButton("Button 2");
// column 1
c.gridx = 1;
// row 0
c.gridy = 0;
// Initialization of object
// "button" of JButton class.
button = new JButton("Button 3");
// column 1
c.gridx = 2;
// row 0
c.gridy = 0;
// Initialization of object
// "button" of JButton class.
button = new JButton("Long-Named Button 4");
// column width 0
c.weightx = 0.0;
// row width 3
c.gridwidth = 3;
// column 1
c.gridx = 0;
// row 1
c.gridy = 1;
// Initialization of object
// "button" of JButton class.
button = new JButton("Button 5");
// bottom of space
c.anchor = GridBagConstraints.PAGE_END;
// top padding
c.insets = new Insets(10, 0, 0, 0);
// column 2
c.gridx = 1;
// 2 columns wide
c.gridwidth = 2;
// row 3
c.gridy = 2;
// Main Method
public static void main(String[] args)
{
Event Handling in Java - The Delegation event model- Events, Event sources, Event
Listeners, Event classes :
An event can be defined as changing the state of an object or behavior by performing actions. Actions can be a button
click, cursor movement, keypress through keyboard or page scrolling, etc.
Classification of Events
Foreground Events
Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are generated due to
interaction by the user on components in Graphic User Interface (GUI). Interactions are nothing but clicking on a button, scrolling
the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur. To handle the events, Java
follows the Delegation Event model.
Syntax:
addTypeListener()
where Type represents the type of event.
An event that indicates that a component-defined action occurred like a button click
ActionEvent ActionListener
or selecting an item from the menu-item list.
AdjustmentEvent AdjustmentListener The adjustment event is emitted by an Adjustable object like Scrollbar.
An event that indicates that a component moved, the size changed or changed its
ComponentEvent ComponentListener
visibility.
When a component is added to a container (or) removed from it, then this event is
ContainerEvent ContainerListener
generated by a container object.
FocusEvent FocusListener These are focus-related events, which include focus, focusin, focusout, and blur.
ItemEvent ItemListener An event that indicates whether an item was selected or not.
KeyEvent KeyListener An event that occurs due to a sequence of keypresses on the keyboard.
MouseListener &
MouseEvent The events that occur due to the user interaction with the mouse (Pointing Device).
MouseMotionListener
MouseWheelEvent MouseWheelListener An event that specifies that the mouse wheel was rotated in a component.
TextEvent TextListener An event that occurs when an object’s text changes.
WindowEvent WindowListener An event which indicates whether a window has changed its status or not.
Note: As Interfaces contains abstract methods which need to implemented by the registered class to handle events.
ActionListener ● actionPerformed()
AdjustmentListener ● adjustmentValueChanged()
● componentResized()
● componentShown()
ComponentListener
● componentMoved()
● componentHidden()
● componentAdded()
ContainerListener
● componentRemoved()
● focusGained()
FocusListener
● focusLost()
ItemListener ● itemStateChanged()
● keyTyped()
KeyListener ● keyPressed()
● keyReleased()
● mousePressed()
● mouseClicked()
MouseListener ● mouseEntered()
● mouseExited()
● mouseReleased()
● mouseMoved()
MouseMotionListener
● mouseDragged()
MouseWheelListener ● mouseWheelMoved()
TextListener ● textChanged()
● windowActivated()
● windowDeactivated()
● windowOpened()
WindowListener ● windowClosed()
● windowClosing()
● windowIconified()
● windowDeiconified()
Within Class
Other Class
Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler may throw errors due to the unavailability of some packages.
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
GFG2 gfgObj;
Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFG3()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
There are two types of events that MouseMotionListener can generate. There are two abstract functions that represent these two
events. The abstract functions are :
void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and dragged. Events
are passed until the user releases the mouse button.
void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to another within the
component, without pressing any mouse buttons.
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");
f.show();
}
// show the point where the user released the mouse click
label1.setText("mouse released at point:"+ e.getX() + " " + e.getY());
}
// show the point through which the mouse exited the frame
label2.setText("mouse exited through point:"+ e.getX() + " " + e.getY());
}
// show the point through which the mouse entered the frame
label2.setText("mouse entered at point:"+ e.getX() + " " + e.getY());
}
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseEventHandler extends JFrame implements MouseListener, MouseMotionListener {
public MouseEventHandler() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at (" + e.getX() + "," + e.getY() + ")");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse dragged at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse moved at (" + e.getX() + "," + e.getY() + ")");
}
public static void main(String[] args) {
MouseEventHandler frame = new MouseEventHandler();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output :
Mouse entered at (277,285)
Mouse moved at (277,285)
Mouse moved at (275,278)
Mouse moved at (273,272)
Mouse moved at (273,268)
Mouse moved at (273,265)
Mouse moved at (273,263)
Mouse moved at (274,263)
Mouse moved at (279,266)
Mouse moved at (289,273)
Mouse exited at (427,402)
KeyBoard Events :
The Java KeyListener in the Abstract Window Toolkit (AWT) is a fundamental tool for achieving this. The KeyListener
Interface is found in “java.awt.event” package. In this article, we’ll explore what the KeyListener is, and its declaration methods, and
supply examples with explanatory comments.
Declaring KeyListener
public interface KeyListener extends EventListener
Methods of Java KeyListener in AWT
The KeyListener port defines three methods that you must implement:
Method Description
Example 1:
Below is the implementation of the Java KeyListener:
// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());
// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());