*****UNIT-1*****
• Introduction & history…
➢ Java is an object oriented programming language,
develoed by sum microsystems in 1991 and in 1995
James goseling ( also knownas father of java) at U.S.A
➢ It is owned by ORACLE and more than 3 billion devices
run java .
➢ It is used for mobile application,desktop application and
web application etc.
➢ Java is a class based, object oriented programming
language that is designed to have as few
implementation dependency as possible.
➢ It is a robust,secured,high performance,portable,multi
threaded language.
Basic structure…
// Import necessary libraries
import [Link].*;
// Declare the class
Public class ClassName{
//main method where program execution begins
Public static void main (string args[]){
// Your code here
}
}
EXAMPLE---------------
Class test {
Public static void main(string args){
[Link](“my first java program.”);
}
}
File →save->d:\[Link]
1)IMPORT STATEMENT –
- Import necessary libraries or classes to use in your program
2)Class- Declare the class with public access modifier, followed
by the class name.
3)Main method- the main method is the entry point of the
program, where execution begins. It’s declared with the public
access modifier, static keyword, and void main return type.
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\//\/\
• Java terminology -------------------------------------
1) JVM ( java virtual machine)
This is generally referred to as jvm there are three
execution phases of a program.
➢ Written
➢ Compile
➢ Run
2) Byte code in the development process ---
The java compiler of jdk compiles the java source code into
bytecode so that it can be executed by JVM, it can be
served as .class
3) JDK( Java development kit---
✓ While we were using the term JDK when we learn
about bytecode and java.
✓ It is a complete Java development kit includes
everything including complier.
4) JRE( java runtime environment)-----
Jdk includes jre. JRE installation on our computers allows
the java program to run.
5) Garbage collector-----------
➢ In java , programmer can’t delete the objects
➢ To delete or recollect that memory JVM has a
program called GARBAGE COLLECTOR.
➢ Garbage collector can recollect the objects that are
not referenced.
6) Class path---:
The classpath is the file path where the java runtime and
java compiler look for .class files to load.
• COMPILATION -:
JDK
DEVLOPMENT
JVM JRE
TOOLS
LIBRARY
[Cite your source here.]
COMPILER
SOURCE JDK
CODE .JAVA BYTE CODE
.CLASS
• Execution-:
J NATIVE
CODE
Byte code JVM
• Features of java--------------------
1) Platform independent
2) Object oriented programming language
3) Simple
4) Robust (strong)
5) Secure
6) Distributed
7) Portable
8) Multi threading
9) Write one run anywhere
• What is syntax ?
Just like we have soe rules that we follow to
speak English , exactly we have some rules to
follow while writing a java program
• Variable’s
A variable is a containers that stores a value. This
value can be changed during the execution of the
program .
Example—
Int Age = 8;
Data type variable value
• Data types→
Data type in java fall under the following category
{DATA TYPE}
PRIMARY (PREMITIVE) USER DEFINED( NON-Primitive)
Class
Interface
Array
Byte string
Short object
Int
Long
Double
Char
Boolean INTEGRAL—( Byte , short,int,long)
DECIMAL-(float , double)
➢ BYTE – range (-128 to +127) takes 1 byte (default value 0)
➢ Short – range(217/2 to 216/2—1) takes 2 byte with .0 default
value
➢ Int- range(-232/2 to 232/2-1) take 4 byte with default 0.0
➢ Long- range(-264/2 to 264/2-1) take 8 byte with default 0
➢ Double – takes 8 byte same as it long
➢ Char- range ( 0 to 65535(216-1) takes 2 byte supports Unicode
➢ Boolean- 0 to 1(0,1) takes 1 bit
➢ Float- takes 4 byte
NOTE-:
In order to choose the data type we first need to
find the type of data we want to store after that
we need to analyse the min & max value we might
use literals.
LITERALS-:
A constant value which can be assigned to the variable is
called as a literal.
Keyword -:
Words which are reserved and used by the java complier
they cannot be used as an identifier.
Keyword Description
abstract A non-access modifier. Used for classes and methods: An abstract cla
cannot be used to create objects (to access it, it must be inherited fro
another class). An abstract method can only be used in an abstract cl
it does not have a body. The body is provided by the subclass (inheri
assert For debugging
boolean A data type that can only store true or false values
break Breaks out of a loop or a switch block
byte A data type that can store whole numbers from -128 and 127
case Marks a block of code in switch statements
catch Catches exceptions generated by try statements
char A data type that is used to store a single character
class Defines a class
continue Continues to the next iteration of a loop
Const Defines a constant. Not in use - use final instead
default Specifies the default block of code in a switch statement
do Used together with while to create a do-while loop
double A data type that can store fractional numbers from 1.7e−308 to 1.7e
else Used in conditional statements
enum Declares an enumerated (unchangeable) type
exports Exports a package with a module. New in Java 9
extends Extends a class (indicates that a class is inherited from another class)
final A non-access modifier used for classes, attributes and methods, whic
them non-changeable (impossible to inherit or override)
finally Used with exceptions, a block of code that will be executed no matter
is an exception or not
float A data type that can store fractional numbers from 3.4e−038 to 3.4e
for Create a for loop
Goto Not in use, and has no function
if Makes a conditional statement
implements Implements an interface
import Used to import a package, class or interface
instanceof Checks whether an object is an instance of a specific class or an inter
int A data type that can store whole numbers from -2147483648 to 2147
interface Used to declare a special type of class that only contains abstract me
long A data type that can store whole numbers from -9223372036854775
9223372036854775808
module Declares a module. New in Java 9
native Specifies that a method is not implemented in the same Java source
in another language)
new Creates new objects
package Declares a package
private An access modifier used for attributes, methods and constructors, ma
them only accessible within the declared class
protected An access modifier used for attributes, methods and constructors, ma
them accessible in the same package and subclasses
public An access modifier used for classes, attributes, methods and construc
making them accessible by any other class
requires Specifies required libraries inside a module. New in Java 9
return Finished the execution of a method, and can be used to return a valu
method
short A data type that can store whole numbers from -32768 to 32767
static A non-access modifier used for methods and attributes. Static
methods/attributes can be accessed without creating an object of a c
Strictfp Obsolete. Restrict the precision and rounding of floating point calcula
super Refers to superclass (parent) objects
switch Selects one of many code blocks to be executed
synchronized A non-access modifier, which specifies that methods can only be acce
one thread at a time
this Refers to the current object in a method or constructor
throw Creates a custom error
throws Indicates what exceptions may be thrown by a method
transient Used to ignore an attribute when serializing an object
try Creates a try...catch statement
var Declares a variable. New in Java 10
void Specifies that a method should not have a return value
volatile Indicates that an attribute is not cached thread-locally, and is always
from the "main memory"
while Creates a while loop
• For input-
Scanner sc = new scanner([Link]);
String name = [Link]();
• For output
[Link](“strings[]”);
❖Operator & expression -:
Operator are used to perform operation on
variable and values
7 + 11 = 18
Operand operand result
Operator
Operator Type Category Precedence
Unary Postfix expr++ expr--
Prefix ++expr --expr +expr -expr ~ !
Arithmetic Multiplicative * / %
Additive + -
Shift Shift << >> >>>
Relational Comparison < > <= >= instanceof
Equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary Ternary ? :
Assignment Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by --x
1
What is operator precedence?
The operator precedence represents how two expressions are bind together. In an
expression, it determines the grouping of operators with operands and decides how
an expression will evaluate.
While solving an expression two things must be kept in mind the first is
a precedence and the second is associativity
Precedence
Precedence is the priority for grouping different types of operators with their
operands. It is meaningful only if an expression has more than one operator with
higher or lower precedence. The operators having higher precedence are evaluated
first. If we want to evaluate lower precedence operators first, we must group operands
by using parentheses and then evaluate.
Java Operator Precedence Table
The following table describes the precedence and associativity of operators used in
Java.
Precedence Operator Type Associativity
15 () Parentheses Left to Right
[] Array subscript
· Member selection
14 ++ Unary post-increment Right to left
-- Unary post-decrement
13 ++ Unary pre-increment Right to left
-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast
12 * Multiplication Left to right
/ Division
% Modulus
11 + Addition Left to right
- Subtraction
10 << Bitwise left shift Left to right
>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
9 < Relational less than Left to right
<= Relational less than or equal
> Relational greater than
>= Relational greater than or equal
instanceof Type comparison (objects only)
8 == Relational is equal to Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
1 = Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
ava Operator Precedence Example
Let's understand the operator precedence through an example. Consider the following
expression and guess the answer.
1. 1 + 5 * 3
You might be thinking that the answer would be 18 but not so. Because the
multiplication (*) operator has higher precedence than the addition (+) operator.
Hence, the expression first evaluates 5*3 and then evaluates the remaining expression
i.e. 1+15. Therefore, the answer will be 16.
QUESTIONS →
Q-1) what is java language?
Q-2) give the basic structure of java
program .
4) Explain the term byte code.
5) Explain – JVM,JDK,JRE.
6) How is java code run? Demonstrate
with suitable diagram.
7) What is garbage collector?
8) What is class path?
9) Explain the features of java.
10) Explain different types datatypes.
Explain with example
11) Explain operator with its types.
1. //write a java program that prints a statement.
Import [Link]*;
Public class java{
Public static void main{
[Link](“my first program of java”);
}
}
Output-
My first java programme
2. // print your details
public class java{
public static void main(String[]args){
[Link]("my name is dhruv sharma");
[Link]("I am pursing bca");
[Link]("my roll no is 42");
}
}
3. // wap to print student information
4.
5. import [Link].*;
6.
7. public class java{
8. public static void main(String[]args){
9. Scanner sc = new Scanner([Link]);
10. [Link]("NAME");
11. String name = [Link]();
12. [Link]("Age");
13. int age = [Link]();
14. [Link]("id");
15. int id = [Link]();
16. [Link]("NAME:"+name);
17. [Link]("AGE:" +age);
18. [Link]("ID:" +id);
19.
20. }
21. }
4.//wap to demonstrate calculator.
//prorgam for all arithmatic opreator//
import [Link];
public class cal{
public static void main(String[] args) {
Float sum,mul,div,subs,module;
Scanner sc = new Scanner([Link]);
[Link]("a");
Float a = [Link]();
[Link]("b");
Float b = [Link]();
sum=a+b;
mul=a*b;
div=a/b;
subs=a-b;
module = a%b;
[Link]("sum is:" +sum);
[Link]("mul is:" +mul);
[Link]("div:" +div);
[Link]("substraction:" +subs);
[Link]("module:" +module);
• Conditional in java→
In java we can execute instructions on a condition
being met.
Conditional statements in programming are used
to control the flow of a program based on
certain conditions.
These statements allow the execution of different
code blocks depending on whether a specified
condition evaluates to true or false, providing a
fundamental mechanism for decision-making in
algorithms.
1. If Conditional Statement:
The if statement is the most basic form of
conditional statement. It checks if a condition is
true. If it is, the program executes a block of
code.
Syntax of If Conditional Statement:
if (condition) {
// code to execute if condition is true
}
if condition is true, the if code block executes.
If false, the execution moves to the next block
to check.
//program for if statement
public class Main {
public static void main(String[] args) {
int x = 10;
// Check if x is greater than 0
if (x > 0) {
[Link]("x is positive"); //
Print a message if x is positive
}
}
}
2. If-Else Conditional Statement:
The if-else statement extends the if statement by adding an else clause.
If the condition is false, the program executes the code in the else block.
Syntax of If-Else Conditional Statement:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
if condition is true, the if code block executes. If false, the execution
moves to the else block.
// program for if else statement
public class Main {
public static void main(String[] args) {
// Define the value of x
int x = -10;
// Check if x is greater than 0
if (x > 0) {
[Link]("x is positive");
} else {
[Link]("x is not positive");
}
}
}
3. if-Else if Conditional Statement:
The if-else if statement allows for multiple conditions to be checked in
sequence. If the if condition is false, the program checks the next else if
condition, and so on.
Syntax of If-Else if Conditional Statement:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if all conditions are false
}
In else if statements, the conditions are checked from the top-down, if
the first block returns true, the second and the third blocks will not be
checked, but if the first if block returns false, the second block will be
checked. This checking continues until a block returns a true outcome.
public class Main {
public static void GFG(int x) {
// Check if the number is positive
if (x > 0) {
[Link]("x is positive");
}
// Check if the number is negative
else if (x < 0) {
[Link]("x is not positive");
}
// If the number is neither positive nor
negative
// it must be zero
else {
[Link]("x is not zero");
}
}
public static void main(String[] args) {
// Test the function with the sample
number
int x = 0;
GFG(x);
}
}
4. Switch Conditional Statement:
The switch statement is used when you need to check a variable against
a series of values. It’s often used as a more readable alternative to a long
if-else if chain.
In switch expressions, each block is terminated by a break keyword. The
statements in switch are expressed with cases.
Switch Conditional Statement Syntax:
switch (variable) {
case value1:
// code to execute if variable equals value1
break;
case value2:
// code to execute if variable equals value2
break;
default:
// code to execute if variable doesn't match any value
}
public class Main {
public static void main(String[] args) {
// Declare and initialize the variable x
int x = 2;
// Use a switch statement to check the
value of x
switch (x) {
// If x is 1, print "x is one"
case 1:
[Link]("x is one");
break;
// If x is 2, print "x is two"
case 2:
[Link]("x is two");
break;
// For any other value of x, print "x is
neither one nor two"
default:
[Link]("x is neither one
nor two");
}
}
}
5. Ternary Expression Conditional Statement:
The ternary operator is a shorthand way of writing an if-else statement.
It takes three operands: a condition, a result for when the condition is
true, and a result for when the condition is false.
Syntax of Ternary Expression:
condition ? result_if_true : result_if_false
public class Main {
public static void main(String[] args)
{
// Define an integer variable x and assign the value
// 10 to it
int x = 10;
// Use a ternary operator to check if x is positive
// or not If x is greater than 0, assign "x is
// positive" to the result variable Otherwise,
// assign "x is not positive" to the result variable
String result = (x > 0) ? "x is positive"
: "x is not positive";
// Print the result to the console
[Link](result);
}
}
Here are ten basic Java programming questions that are commonly asked to test fundamental
knowledge and skills:
1. Write a Java program to print "Hello, World!" to the console.
2. Write a Java program to calculate the sum of two numbers entered by the user.
3. Write a Java program to find the largest of three numbers entered by the user.
4. Write a Java program to check if a given number is even or odd.
5. Write a Java program to display the multiplication table of a given number.
6. Write a Java program to reverse a string provided by the user.
7. Write a Java program to find the factorial of a number using both iterative and
recursive methods.
8. Write a Java program to check if a given string is a palindrome (reads the same
forwards and backwards).
9. Write a Java program to find the Fibonacci sequence up to a given number of
terms.
10. Write a Java program to sort an array of integers in ascending order.
These questions cover a range of basic concepts including input/output, conditionals, loops,
recursion, and array manipulation.
Certainly! Here are 20 basic Java programming questions that involve printing, operators, and
conditional statements:
Printing
1. Write a Java program to print your name and age.
2. Write a Java program to print a user-provided integer and its square.
3. Write a Java program to print the first 10 natural numbers (1 through 10) in one
line separated by commas.
4. Write a Java program to print a formatted table showing the squares of
numbers from 1 to 10.
5. Write a Java program to print a right-angled triangle of numbers with the base
and height of 5.
6. Write a Java program to print the current date and time in a human-readable
format.
7. Write a Java program to print a user's input string in uppercase.
8. Write a Java program to print a sequence of even numbers from 2 to 20 in a
single line.
9. Write a Java program to print the multiplication table of 7.
10. Write a Java program to print a given number's multiplication table up to 10.
Operators
11. Write a Java program to swap two variables using a temporary variable.
12. Write a Java program to check whether a number is divisible by both 5 and 7
using the modulo operator.
13. Write a Java program to calculate the area of a rectangle given its width and
height using arithmetic operators.
14. Write a Java program to determine whether a given number is positive, negative,
or zero using conditional statements.
15. Write a Java program to perform basic arithmetic operations (addition,
subtraction, multiplication, division) based on user input.
16. Write a Java program to find the average of three numbers using arithmetic
operators.
17. Write a Java program to check if a given year is a leap year using conditional
statements and the modulo operator.
18. Write a Java program to convert a temperature from Celsius to Fahrenheit
using arithmetic operators.
19. Write a Java program to find the largest of three numbers using conditional
statements and comparison operators.
20. Write a Java program to check if a given number is a multiple of 3 or 5 using
conditional statements.
These questions cover a range of basic concepts including printing outputs, using various
operators (arithmetic, relational, and logical), and applying conditional logic.
LOOPS-→
➢ Sometimes we want our programs to execute
a few set of instructions over and over again.
➢ Loops make it easy for us to tell the
computer that a given set of instructions
need to be executed repeatedly.
• Types→
1) For loop
2) While loop
3) Do-while loop
4) Infinite loop
1) For loop→
Syntax->
For(initialisation ; condition;updation)
{
// do something
}
1. //Java Program to demonstrate the example of for loop
2. //which prints table of 1
3. public class ForExample {
4. public static void main(String[] args) {
5. //Code of Java for loop
6. for(int i=1;i<=10;i++){
7. [Link](i);
8. }
9. }
10. }
Output:
1
2
3
4
5
6
7
8
9
10
Java Nested for Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner
loop executes completely whenever outer loop executes.
1. public class NestedForExample {
2. public static void main(String[] args) {
3. //loop of i
4. for(int i=1;i<=3;i++){
5. //loop of j
6. for(int j=1;j<=3;j++){
7. [Link](i+" "+j);
8. }//end of i
9. }//end of j
10. }
11. }
12. Output:
13. 1 1
14. 1 2
15. 1 3
16. 2 1
17. 2 2
18. 2 3
19. 3 1
20. 3 2
21. Java for Loop vs while Loop vs do-while Loop
Comparison for loop while loop do-while loop
Introduction The Java for loop is a control The Java while loop is a The Java do while loop is a
flow statement that iterates a control flow statement control flow statement
part of the programs multiple that executes a part of that executes a part of the
times. the programs repeatedly programs at least once and
on the basis of given the further execution
boolean condition. depends upon the given
boolean condition.
When to use If the number of iteration is If the number of iteration If the number of iteration is
fixed, it is recommended to is not fixed, it is not fixed and you must
use for loop. recommended to use have to execute the loop at
while loop. least once, it is
recommended to use the
do-while loop.
Syntax for(init;condition;incr/decr){ while(condition){ do{
// code to be executed //code to be executed //code to be executed
} } }while(condition);
Example //for loop //while loop //do-while loop
for(int i=1;i<=10;i++){ int i=1; int i=1;
[Link](i); while(i<=10){ do{
} [Link](i); [Link](i);
i++; i++;
} }while(i<=10);
Syntax for for(;;){ while(true){ do{
infinitive loop //code to be executed //code to be executed //code to be executed
} } }while(true);
While Loop
The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false,
the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is
not fixed, it is recommended to use the while loop.
Syntax:
1. while (condition){
2. //code to be executed
3. I ncrement / decrement statement
4. }
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.
[Link]
1. public class WhileExample {
2. public static void main(String[] args) {
3. int i=1;
4. while(i<=10){
5. [Link](i);
6. i++;
7. }
8. }
9. }
Output:
1
2
3
4
5
6
7
8
9
10
Java do-while Loop
The Java do-while loop is used to iterate a part of the program repeatedly, until the
specified condition is true. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for
loop, the do-while check the condition at the end of loop body. The Java do-while
loop is executed at least once because condition is checked after loop body.
Syntax:
1. do{
2. //code to be executed / loop body
3. //update statement
4. }while (condition);
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.
[Link]
1. public class DoWhileExample {
2. public static void main(String[] args) {
3. int i=1;
4. do{
5. [Link](i);
6. i++;
7. }while(i<=10);
8. }
9. }
Output:
1
2
3
4
5
6
7
8
9
10
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the
current flow of the program at specified condition. In case of inner loop, it breaks only
inner loop.
We can use Java break statement in all types of loops such as for loop, while
loop and do-while loop.
Syntax:
1. jump-statement;
2. break;
Java Break Statement with Loop
Example:
[Link]
1. //Java Program to demonstrate the use of break statement
2. //inside the for loop.
3. public class BreakExample {
4. public static void main(String[] args) {
5. //using for loop
6. for(int i=1;i<=10;i++){
7. if(i==5){
8. //breaking the loop
9. break;
10. }
11. [Link](i);
12. }
13. }
14. }
Output:
1
2
3
4
Infinite Loop in java
Infinite loop in java refers to a situation where a condition is setup so that your loop
continues infinitely without a stop. A loop statement is used to iterate statements or
expressions for a definite number of times but sometimes we may need to iterate not
for a fixed number but infinitely. For such situations, we need infinite loops in java.
There are basically three looping structures in java: for, while and do while.
These structures are used for iterations i.e., these statements can allow the repetition
of a set of statements or functions. While using them for infinite repetitions, we may
use the following ways.
The syntax of a for loop goes like this:
for(variable_initialization ; condition ; updation)
//set of statement(s)/ expressions to be repeated .
Example:
for(int i=0; i<2; i++)
[Link]("Hello World");
It will print:
Hello World
Hello World
Now, if we want to make our for loop go infinitely, we can try the following ways:
class example
public static void main(String args[])
for(int i=1; i>0; i++)
[Link]("Hello World");
This program will print “Hello World” infinitely since the condition “i>0” will always
be true.
This is a rather an unintentional and tedious way of doing this. You would probably
never want to do things like printing “Hello world” an infinite number of times. This
would probably be a programming error. But using infinite loops can also be
intentional according to the requirements of a program. An elegant way of writing
infinite loops are given below.
What is Infinite Loop in Java?
An infinite loop in java is a sequence of instructions that loops indefinitely
until the system crashes. In Java, an infinite loop occurs when the loop’s
ending condition is not met. An endless loop in Java is usually a
programming error, but it can sometimes be used intentionally, such as in a
wait condition.
All loops, including while, for, and do-while loops, have one feature: the
condition. Loops are conducted until the condition is satisfied. In this
article, we will look at the case where the condition always evaluates to
true, i.e. it never fails.
This will result in an indefinite loop that will continue to run until the
application is terminated or the system crashes.
In most circumstances, infinite loops are produced as a result of a
programming error, but in certain cases, infinite loops are purposely made
in order for some code to run on a regular basis.
These loops are only halted when the application is terminated or the
system fails.
/* package whatever; // don't place package name! */
import [Link].*;
import [Link].*;
import [Link].*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
public static void main (String[] args) throws [Link]
// code implementation starts from here
for(int i=5;i>0;){
[Link]("PrepBytes");
}
Certainly! Here are 20 basic Java programming questions focused on loops:
1. Write a Java program to print numbers from 1 to 10 using a for loop.
2. Write a Java program to print the first 10 even numbers using a while loop.
3. Write a Java program to print the factorial of a number using a for loop.
4. Write a Java program to calculate the sum of all numbers from 1 to 100 using a
while loop.
5. Write a Java program to print the multiplication table of a given number using a
for loop.
6. Write a Java program to find the largest number in an array using a for loop.
7. Write a Java program to reverse a given integer using a while loop.
8. Write a Java program to display the Fibonacci sequence up to a specified
number of terms using a for loop.
9. Write a Java program to count the number of digits in a number using a while
loop.
10. Write a Java program to find the sum of all odd numbers between 1 and 50
using a for loop.
11. Write a Java program to print a right-angled triangle pattern of stars with a
height of 5 using nested for loops.
12. Write a Java program to print a multiplication table (from 1 to 10) for numbers
1 through 5 using nested for loops.
13. Write a Java program to compute the sum of all elements in an array using a for
loop.
14. Write a Java program to print a diamond pattern of stars with a height of 5
using nested for loops.
15. Write a Java program to find all prime numbers between 1 and 100 using a for
loop.
16. Write a Java program to generate a list of numbers in a sequence where each
number is the sum of the previous two, up to 20 terms, using a while loop.
17. Write a Java program to print the numbers from 10 down to 1 using a for loop.
18. Write a Java program to find and print all the perfect numbers between 1 and
1000 using a for loop.
19. Write a Java program to count the number of vowels in a given string using a
for loop.
20. Write a Java program to print a pattern of numbers (like Pascal’s Triangle) up
to a given number of rows using nested for loops.
These questions cover a range of loop-related topics including iteration, nested loops, pattern
printing, and basic algorithmic challenges
Function: Within a programme, a function can be called to carry out a specific task. It
is a self-contained block of code. It takes input parameters (if any) and can return a
value or perform actions.
Method: The Method's operation is similar to that of a function in that it may accept
input parameters or arguments and can also return data by having a return type.
However, it differs from a function in two key ways.
1. A method is connected or related to the object instance it is called using.
2. The Method can only operate upon data present in the class in which it is
placed.
3. It's a key concept in object-oriented programming.
Difference Between Function and Method
Functions Methods
Do not have reference variables. Are called by reference variable.
It does not have access control, i.e., it can be It contains access control, therefore only within
declared and defined anywhere in the code. the class should it be declared and defined.
Both object-oriented and non-object-oriented Only object-oriented programming languages
languages are compatible with the Function. can use methods.
It is called individually and by its name. It is called using the name or reference of its
object.
As it is called individually, the data is passed As it is called dependently, the data is passed
externally or explicitly. internally or implicitly.
java Methods→
The method in Java or Methods of Java is a
collection of statements that perform some
specific tasks and return the result to the
caller. A Java method can perform some
specific tasks without returning anything.
Java Methods allows us to reuse the code
without retyping the code. In Java, every
method must be part of some class that is
different from languages like C, C++, and
Python.
A method is like a function i.e. used to
expose the behavior of an object.
It is a set of codes that perform a particular
task.
Syntax of Method:
<access_modifier> <return_type>
<method_name>( list_of_parameters)
{
//body
}
Types of Methods in Java
There are two types of methods in Java:
1. Predefined Method
In Java, predefined methods are the method
that is already defined in the Java class
libraries is known as predefined methods. It
is also known as the standard library method
or built-in method. We can directly use these
methods just by calling them in the program
at any point.
2. User-defined Method
The method written by the user or
programmer is known as a user-defined
method. These methods are modified
according to the requirement.
Ways to Create Method in Java
There are two ways to create a method in
Java:
1. Instance Method: Access the instance
data using the object name. Declared inside
a class.
Syntax:
// Instance Method
void method_name(){
body // instance area
}
2. Static Method: Access the static data using
class name. Declared inside class
with static keyword.
Syntax:
//Static Method
static void method_name(){
body // static area
}
Method Signature:
It consists of the method name and a
parameter list (number of parameters, type
of the parameters, and order of the
parameters). The return type and exceptions
are not considered as part of it.
Method Signature of the above function:
max(int x, int y) Number of parameters is 2,
Type of parameter is int.
Naming a Method
In Java language method name is typically a
single word that should be a verb in
lowercase or a multi-word, that begins with
a verb in lowercase followed by an adjective,
noun. After the first word, the first letter of
each word should be capitalized.
Rules to Name a Method:
• While defining a method, remember that the
method name must be a verb and start with
a lowercase letter.
• If the method name has more than two words, the
first name must be a verb followed by an adjective
or noun.
• In the multi-word method name, the first letter of
each word must be in uppercase except the first
word. For example, findSum, computeMax, setX,
and getX.
Generally, a method has a unique name
within the class in which it is defined but
sometimes a method might have the same
name as other method names within the
same class as method overloading is allowed
in Java .
Method Calling
The method needs to be called for use its
functionality. There can be three situations
when a method is called:
A method returns to the code that invoked it
when:
• It completes all the statements in the method.
• It reaches a return statement.
• Throws an exception.
// Java Program to Illustrate Methods
// Importing required classes
import [Link].*;
// Class 1
// Helper class
class Addition {
// Initially taking sum as 0
// as we have not started computation
int sum = 0;
// Method
// To add two numbers
public int addTwoInt(int a, int b)
{
// Adding two integer value
sum = a + b;
// Returning summation of two values
return sum;
}
}
// Class 2
// Helper class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of class 1 inside main()
method
Addition add = new Addition();
// Calling method of above class
// to add two integer
// using instance created
int s = [Link](1, 2);
// Printing the sum of two numbers
[Link]("Sum of two integer
values :"
+ s);
}
}
Recursion in Java
Last Updated : 12 Jul, 2024
••
RECURSION→
In Java, Recursion is a process in which a function calls itself directly or
indirectly is called recursion and the corresponding function is called a
recursive function.
Base Condition in Recursion
In the recursive program, the solution to the base case
is provided and the solution to the bigger problem is
expressed in terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, the base case for n < = 1 is
defined and the larger value of a number can be solved
by converting it to a smaller one till the base case is
reached.
Working of Recursion
The idea is to represent a problem in terms of one or
more smaller sub-problems and add base conditions
that stop the recursion. For example, we compute
factorial n if we know the factorial of (n-1). The base
case for factorial would be n = 0. We return 1 when n =
0.
// Java Program to implement
// Factorial using recursion
class GFG {
// recursive method
int fact(int n)
{
int result;
if (n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
}
// Driver Class
class Recursion {
// Main function
public static void main(String[] args)
{
GFG f = new GFG();
[Link]("Factorial of 3 is "
+ [Link](3));
[Link]("Factorial of 4 is "
+ [Link](4));
[Link]("Factorial of 5 is "
+ [Link](5));
}
}
// Java Program to implement
// Fibonacci Series
import [Link].*;
// Driver Function
class GFG {
// Function to return Fibonacci value
static int Fib(int N)
{
if (N == 0 || N == 1)
return N;
return Fib(N - 1) + Fib(N - 2);
}
// Main function
public static void main(String[] args)
{
// Fibonacci of 3
[Link]("Fibonacci of " + 3 + "
"
+ Fib(3));
// Fibonacci of 4
[Link]("Fibonacci of " + 4 + "
"
+ Fib(4));
// Fibonacci of 5
[Link]("Fibonacci of " + 5 + "
"
+ Fib(5));
}
}
Time Complexity and Space Complexity
Generally, there is always more than one way
to solve a problem in computer science with
different algorithms. Therefore, it is highly
required to use a method to compare the
solutions in order to judge which one is more
optimal. The method must be:
• Independent of the machine and its configuration,
on which the algorithm is running on.
• Shows a direct correlation with the number of
inputs.
• Can distinguish two algorithms clearly without
ambiguity.
There are two such methods used, time
complexity and space complexity which are
discussed below:
Time Complexity: The time complexity of an
algorithm quantifies the amount of time
taken by an algorithm to run as a function of
the length of the input. Note that the time to
run is a function of the length of the input
and not the actual execution time of the
machine on which the algorithm is running
on.
Definition–
The valid algorithm takes a finite amount of
time for execution. The time required by the
algorithm to solve given problem is
called time complexity of the algorithm.
Time complexity is very useful measure in
algorithm analysis.
It is the time needed for the completion of
an algorithm. To estimate the time
complexity, we need to consider the cost of
each fundamental instruction and the
number of times the instruction is executed.
Example 1: Addition of two scalar variables.
Algorithm ADD SCALAR(A, B)
//Description: Perform arithmetic addition of
two numbers
//Input: Two scalar variables A and B
//Output: variable C, which holds the
addition of A and B
C <- A + B
return C
The addition of two scalar numbers requires
one addition operation. the time complexity
of this algorithm is constant, so T(n) = O(1) .
In order to calculate time complexity on an
algorithm, it is assumed that a constant time
c is taken to execute one operation, and then
the total operations for an input length
on N are calculated. Consider an example to
understand the process of calculation:
Suppose a problem is to find whether a
pair (X, Y) exists in an array, A of N elements
whose sum is Z. The simplest idea is to
consider every pair and check if it satisfies
the given condition or not.
The pseudo-code is as follows:
int a[n];
for(int i = 0;i < n;i++)
cin >> a[i]
for(int i = 0;i < n;i++)
for(int j = 0;j < n;j++)
if(i!=j && a[i]+a[j] == z)
return true
return false
// Java program for the above approach
import [Link].*;
import [Link].*;
class GFG{
// Function to find a pair in the given
// array whose sum is equal to z
static boolean findPair(int a[], int n, int z)
{
// Iterate through all the pairs
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
// Check if the sum of the pair
// (a[i], a[j]) is equal to z
if (i != j && a[i] + a[j] == z)
return true;
return false;
}
// Driver code
public static void main(String[] args)
{
// Given Input
int a[] = { 1, -2, 1, 0, 5 };
int z = 0;
int n = [Link];
// Function Call
if (findPair(a, n, z))
[Link]("True");
else
[Link]("False");
}
}
Some general time complexities are listed below with the input range for
which they are accepted in competitive programming:
Input Worst Accepted Time
Usually type of solutions
Length Complexity
10 -12 O(N!) Recursion and backtracking
Input Worst Accepted Time
Usually type of solutions
Length Complexity
Recursion, backtracking, and bit
15-18 O(2N * N)
manipulation
Recursion, backtracking, and bit
18-22 O(2N * N)
manipulation
O(2N/2 * Meet in the middle, Divide and
30-40
N) Conquer
100 O(N4) Dynamic programming, Constructive
400 O(N3) Dynamic programming, Constructive
Dynamic programming, Binary
2K O(N2* log N) Search, Sorting,
Divide and Conquer
Dynamic programming, Graph, Trees,
10K O(N2)
Constructive
Sorting, Binary Search, Divide and
1M O(N* log N)
Conquer
Constructive, Mathematical, Greedy
100M O(N), O(log N), O(1)
Algorithms
Space Complexity:
Definition –
Problem-solving using computer requires memory to hold temporary
data or final result while the program is in execution. The amount of
memory required by the algorithm to solve given problem is called space
complexity of the algorithm.
The space complexity of an algorithm quantifies the amount of space
taken by an algorithm to run as a function of the length of the input.
Consider an example: Suppose a problem to find the frequency of array
elements.
It is the amount of memory needed for the completion of an algorithm.
To estimate the memory requirement we need to focus on two parts:
(1) A fixed part: It is independent of the input size. It includes memory
for instructions (code), constants, variables, etc.
(2) A variable part: It is dependent on the input size. It includes memory
for recursion stack, referenced variables, etc.
Example : Addition of two scalar variables
Algorithm ADD SCALAR(A, B)
//Description: Perform arithmetic addition of two numbers
//Input: Two scalar variables A and B
//Output: variable C, which holds the addition of A and B
C <— A+B
return C
The pseudo-code is as follows:
int freq[n];
int a[n];
for(int i = 0; i<n; i++)
{
cin>>a[i];
freq[a[i]]++;
}
// Java program for the above approach
import [Link].*;
class GFG{
// Function to count frequencies of array items
static void countFreq(int arr[], int n)
{
HashMap<Integer,Integer> freq = new HashMap<>();
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
if([Link](arr[i])){
[Link](arr[i], [Link](arr[i])+1);
}
else{
[Link](arr[i], 1);
}
}
// Traverse through map and print frequencies
for ([Link]<Integer,Integer> x : [Link]())
[Link]([Link]()+ " " + [Link]() +"\n");
}
// Driver Code
public static void main(String[] args)
{
// Given array
int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
int n = [Link];
// Function Call
countFreq(arr, n);
}
}
Completed unit 1-2-3.
-------------------------ARRAY-------------------------
Arrays are fundamental structures in Java that
allow us to store multiple values of the same type
in a single variable. They are useful for managing
collections of data efficiently. Arrays in Java work
differently than they do in C/C++.
-Java array is an object which contains elements
of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory
location. It is a data structure where we store
similar elements. We can store only a fixed set of
elements in a Java array.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
• 1-d array------
Syntax --
Type[]arrayname=new type[size];
Declaration –
Int [] marks = new int[8];
1. ./Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<[Link];i++)//length is the property of array
13. [Link](a[i]);
14. }}
Output:
10
20
70
40
50
/Java Program to illustrate the use of declaration, instantiation
1. //and initialization of Java array in a single line
2. class Testarray1{
3. public static void main(String args[]){
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5. //printing array
6. for(int i=0;i<[Link];i++)//length is the property of array
7. [Link](a[i]);
8. }}
Output:
33
3
4
5
• Multi-dimensions array-(2d-3d )
Syntax ---
Type[][]array name = new type [row][column];
Declaration –
Int [][] matrix = new int[3][3];
Example to initialize Multidimensional Array in Java
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
//Java Program to illustrate the use of multidimensional array
1. class Testarray3{
2. public static void main(String args[]){
3. //declaring and initializing 2D array
4. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
5. //printing 2D array
6. for(int i=0;i<3;i++){
7. for(int j=0;j<3;j++){
8. [Link](arr[i][j]+" ");
9. }
10. [Link]();
11. }
12. }}
123
245
445
1. //Java Program to illustrate the jagged array
2. class TestJaggedArray{
3. public static void main(String[] args){
4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
7. arr[1] = new int[4];
8. arr[2] = new int[2];
9. //initializing a jagged array
10. int count = 0;
11. for (int i=0; i<[Link]; i++)
12. for(int j=0; j<arr[i].length; j++)
13. arr[i][j] = count++;
14.
15. //printing the data of a jagged array
16. for (int i=0; i<[Link]; i++){
17. for (int j=0; j<arr[i].length; j++){
18. [Link](arr[i][j]+" ");
19. }
20. [Link]();//new line
21. }
22. }
23. }
012
3456
78
Addition of 2 Matrices in Java
Let's see a simple example that adds two matrices.
1. //Java Program to demonstrate the addition of two matrices in Java
2. class Testarray5{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
8. //creating another matrix to store the sum of two matrices
9. int c[][]=new int[2][3];
10.
11. //adding and printing addition of 2 matrices
12. for(int i=0;i<2;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=a[i][j]+b[i][j];
15. [Link](c[i][j]+" ");
16. }
17. [Link]();//new line
18. }
19.
20. }}
268
6 8 10
Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is
multiplied by all the columns of the second matrix which can be understood
by the image given below.
1. //Java Program to multiply two matrices
2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11. //multiplying and printing multiplication of 2 matrices
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=0;
15. for(int k=0;k<3;k++)
16. {
17. c[i][j]+=a[i][k]*b[k][j];
18. }//end of k loop
19. [Link](c[i][j]+" "); //printing matrix element
20. }//end of j loop
21. [Link]();//new line
22. }
23. }}
666
12 12 12
18 18 18
1) Java Program to copy all elements of one array into
another array
2) Java Program to find the frequency of each element in
the array
3) Java Program to left rotate the elements of an array
4) Java Program to print the duplicate elements of an array
5) Java Program to print the elements of an array
6) Java Program to print the elements of an array in reverse
order
7) Java Program to print the elements of an array present
on even position
8) Java Program to print the elements of an array present
on odd position
9) Java Program to print the largest element in an array
10) Java Program to print the smallest element in an array
11) Java Program to print the number of elements present
in an array
12) Java Program to print the sum of all the items of the
array
13) Java Program to right rotate the elements of an array
14) Java Program to sort the elements of an array in
ascending order
15) Java Program to sort the elements of an array in
descending order
16) Find 3rd Largest Number in an Array
17) Find 2nd Largest Number in an Array
18) Find Largest Number in an Array
19) Find 2nd Smallest Number in an Array
20) Find Smallest Number in an Array
21) Remove Duplicate Element in an Array
22) Add Two Matrices
23) Multiply Two Matrices
24) Print Odd and Even Number from an Array
25) Transpose matrix
26) Java Program to subtract the two matrices
27) Java Program to determine whether a given matrix is an
identity matrix
28) Java Program to determine whether a given matrix is a
sparse matrix
29) Java Program to determine whether two matrices are
equal
30) Java Program to display the lower triangular matrix
31) Java Program to display the upper triangular matrix
32) Java Program to find the frequency of odd & even
numbers in the given matrix
33) Java Program to find the product of two matrices
34) Java Program to find the sum of each row and each
column of a matrix
35) Java Program to find the transpose of a given matrix
Example: 3-dimensional Array
class ThreeArray {
public static void main(String[] args) {
// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
// for..each loop to iterate through elements of 3d array
for (int[][] array2D: test) {
for (int[] array1D: array2D) {
for(int item: array1D) {
[Link](item);
}
}
}
}
}
Run Code
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3
Example: Program to Multiply Two Matrices
public class MultiplyMatrices {
public static void main(String[] args) {
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };
// Mutliplying Two matrices
int[][] product = new int[r1][c2];
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
// Displaying the result
[Link]("Multiplication of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
[Link](column + " ");
}
[Link]();
}
}
}
Output
Multiplication of two matrices is:
24 29
6 25
List Interface in Java
The List interface is found in [Link] package and inherits the Collection
interface. It is a factory of the ListIterator interface. Through the
ListIterator, we can iterate the list in forward and backward directions.
The implementation classes of the List interface are ArrayList, LinkedList,
Stack, and Vector. ArrayList and LinkedList are widely used in Java
programming. The Vector class is deprecated since Java 5.
Declaration of Java List Interface
public interface List<E> extends Collection<E> ;
Syntax of Java List:
This type of safelist can be defined as:
List<Obj> list = new ArrayList<Obj> ();
Let us start with a simple Java code snippet that demonstrates how to
create and use a List in Java.
Java
import [Link];
import [Link];
public class ListExample {
public static void main(String args[]) {
// Create a List of Strings
List<String> list = new ArrayList<>();
//here, write different operations in List
// Displaying the List
[Link]("List elements: " + list);
}
}
Output
List elements: []
The List interface in Java provides a way to store the ordered collection.
It is a child interface of Collection. It is an ordered collection of objects in
which duplicate values can be stored. Since List preserves the insertion
order, it allows positional access and insertion of elements.
// Java program to Demonstrate List Interface
// Importing all utility classes
import [Link].*;
// Main class
// ListDemo class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of List interface
// implemented by the ArrayList class
List<Integer> l1 = new ArrayList<Integer>();
// Adding elements to object of List interface
// Custom inputs
[Link](0, 1);
[Link](1, 2);
// Print the elements inside the object
[Link](l1);
// Now creating another object of the List
// interface implemented ArrayList class
// Declaring object of integer type
List<Integer> l2 = new ArrayList<Integer>();
// Again adding elements to object of List interface
// Custom inputs
[Link](1);
[Link](2);
[Link](3);
// Will add list l2 from 1 index
[Link](1, l2);
[Link](l1);
// Removes element from index 1
[Link](1);
// Printing the updated List 1
[Link](l1);
// Prints element at index 3 in list 1
// using get() method
[Link]([Link](3));
// Replace 0th element with 5
// in List 1
[Link](0, 5);
// Again printing the updated List 1
[Link](l1);
}
}
Output
[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]
Now let us perform various operations using List Interface to have a better
understanding of the same. We will be discussing the following operations listed
below and later on implementing them via clean Java codes.
Operations in a Java List Interface
Since List is an interface, it can be used only with a class that implements this
interface. Now, let’s see how to perform a few frequently used operations on the
List.
• Operation 1: Adding elements to List class using add() method
• Operation 2: Updating elements in List class using set() method
• Operation 3: Searching for elements using indexOf(), lastIndexOf
methods
• Operation 4: Removing elements using remove() method
• Operation 5: Accessing Elements in List class using get() method
• Operation 6: Checking if an element is present in the List class using
contains() method
Now let us discuss the operations individually and implement the same in the code
to grasp a better grip over it.
1. Adding elements to List class using add() method
In order to add an element to the list, we can use the add() method. This method is
overloaded to perform multiple operations based on different parameters.
Parameters: It takes 2 parameters, namely:
• add(Object): This method is used to add an element at the end of the
List.
• add(int index, Object): This method is used to add an element at a
specific index in the List
Example:
Java
// Java Program to Add Elements to a List
// Importing all utility classes
import [Link].*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of List interface,
// implemented by ArrayList class
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
// Custom elements
[Link]("Geeks");
[Link]("Geeks");
[Link](1, "For");
// Print all the elements inside the
// List interface object
[Link](al);
}
}
Output
[Geeks, For, Geeks]
2. Updating elements
After adding the elements, if we wish to change the element, it can be done using
the set() method. Since List is indexed, the element which we wish to change is
referenced by the index of the element. Therefore, this method takes an index and
the updated element which needs to be inserted at that index.
Example:
Java
// Java Program to Update Elements in a List
// Importing utility classes
import [Link].*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of List interface
List<String> al = new ArrayList<>();
// Adding elements to object of List class
[Link]("Geeks");
[Link]("Geeks");
[Link](1, "Geeks");
// Display theinitial elements in List
[Link]("Initial ArrayList " + al);
// Setting (updating) element at 1st index
// using set() method
[Link](1, "For");
// Print and display the updated List
[Link]("Updated ArrayList " + al);
}
}
Output
Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]
3. Searching for elements
Searching for elements in the List interface is a common operation in Java
programming. The List interface provides several methods to search for elements,
such as the indexOf(), lastIndexOf() methods.
The indexOf() method returns the index of the first occurrence of a specified
element in the list, while the lastIndexOf() method returns the index of the last
occurrence of a specified element.
Parameters:
• indexOf(element): Returns the index of the first occurrence of the
specified element in the list, or -1 if the element is not found
•lastIndexOf(element): Returns the index of the last occurrence of the
specified element in the list, or -1 if the element is not found
Example:
Java
import [Link];
import [Link];
public class ListExample {
public static void main(String[] args)
{
// create a list of integers
List<Integer> numbers = new ArrayList<>();
// add some integers to the list
[Link](1);
[Link](2);
[Link](3);
[Link](2);
// use indexOf() to find the first occurrence of an
// element in the list
int index = [Link](2);
[Link](
"The first occurrence of 2 is at index "
+ index);
// use lastIndexOf() to find the last occurrence of
// an element in the list
int lastIndex = [Link](2);
[Link](
"The last occurrence of 2 is at index "
+ lastIndex);
}
}
Output
The first occurrence of 2 is at index 1
The last occurrence of 2 is at index 3
4. Removing Elements
In order to remove an element from a list, we can use the remove() method. This
method is overloaded to perform multiple operations based on different
parameters. They are:
Parameters:
• remove(Object): This method is used to simply remove an object from
the List. If there are multiple such objects, then the first occurrence of the
object is removed.
•
remove(int index): Since a List is indexed, this method takes an integer
value which simply removes the element present at that specific index in
the List. After removing the element, all the elements are moved to the
left to fill the space and the indices of the objects are updated.
Example:
Java
// Java Program to Remove Elements from a List
// Importing List and ArrayList classes
// from [Link] package
import [Link];
import [Link];
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating List class object
List<String> al = new ArrayList<>();
// Adding elements to the object
// Custom inputs
[Link]("Geeks");
[Link]("Geeks");
// Adding For at 1st indexes
[Link](1, "For");
// Print the initialArrayList
[Link]("Initial ArrayList " + al);
// Now remove element from the above list
// present at 1st index
[Link](1);
// Print the List after removal of element
[Link]("After the Index Removal " + al);
// Now remove the current object from the updated
// List
[Link]("Geeks");
// Finally print the updated List now
[Link]("After the Object Removal "
+ al);
}
}
Output
Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
5. Accessing Elements
In order to access an element in the list, we can use the get() method, which returns
the element at the specified index
Parameters:
get(int index): This method returns the element at the specified index in the list.
Example:
Java
// Java Program to Access Elements of a List
// Importing all utility classes
import [Link].*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of List interface,
// implemented by ArrayList class
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
[Link]("Geeks");
[Link]("For");
[Link]("Geeks");
// Accessing elements using get() method
String first = [Link](0);
String second = [Link](1);
String third = [Link](2);
// Printing all the elements inside the
// List interface object
[Link](first);
[Link](second);
[Link](third);
[Link](al);
}
}
Output
Geeks
For
Geeks
[Geeks, For, Geeks]
6. Checking if an element is present in the List
In order to check if an element is present in the list, we can use
the contains() method. This method returns true if the specified element is present
in the list, otherwise, it returns false.
Parameters:
contains(Object): This method takes a single parameter, the object to be checked if
it is present in the list.
Example:
Java
// Java Program to Check if an Element is Present in a List
// Importing all utility classes
import [Link].*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of List interface,
// implemented by ArrayList class
List<String> al = new ArrayList<>();
// Adding elements to object of List interface
[Link]("Geeks");
[Link]("For");
[Link]("Geeks");
// Checking if element is present using contains()
// method
boolean isPresent = [Link]("Geeks");
// Printing the result
[Link]("Is Geeks present in the list? "
+ isPresent);
}
}
Output
Is Geeks present in the list? true
1. ArrayList
An ArrayList class which is implemented in the collection framework
provides us with dynamic arrays in Java. Though, it may be slower than
standard arrays but can be helpful in programs where lots of
manipulation in the array is needed. Let’s see how to create a list object
using this class.
Example:
Java
// Java program to demonstrate the
// creation of list object using the
// ArrayList class
import [Link].*;
import [Link].*;
class GFG {
public static void main(String[] args)
{
// Size of ArrayList
int n = 5;
// Declaring the List with initial size n
List<Integer> arrli = new ArrayList<Integer>(n);
// Appending the new elements
// at the end of the list
for (int i = 1; i <= n; i++)
[Link](i);
// Printing elements
[Link](arrli);
// Remove element at index 3
[Link](3);
// Displaying the list after deletion
[Link](arrli);
// Printing elements one by one
for (int i = 0; i < [Link](); i++)
[Link]([Link](i) + " ");
}
}
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
--------------------------- STRING--------------------------
Java String
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:
1. char[] ch={'d','h','r','u','v','s','h','a','r','m'};
2. String s=new String(ch);
String s="javatpoint";
Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
The [Link] class
implements Serializable, Comparable and CharSequence interface
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can
create strings in Java by using these three classes
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The [Link] class is used to create
a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is created
and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
Note: String objects are stored in a special memory area known as the "string
constant pool"
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).
) By new keyword
1. String s=new String("Welcome");//creates two objects and one refere
nce variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).
Java String Example
[Link]
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keywo
rd
7. [Link](s1);
8. [Link](s2);
9. [Link](s3);
10. }}
11. Output:
12. java
13. strings
14. example
Java String class methods
The [Link] class provides many useful methods to perform operations
on sequence of char values.
No. Method Description
It returns char value for
1 char charAt(int index)
the particular index
2 int length() It returns string length
static String format(String It returns a formatted
3
format, Object... args) string.
static String format(Locale
It returns formatted string
4 l, String format, Object...
with given locale.
args)
String substring(int It returns substring for
5
beginIndex) given begin index.
It returns substring for
String substring(int
6 given begin index and
beginIndex, int endIndex)
end index.
It returns true or false
boolean
7 after matching the
contains(CharSequence s)
sequence of char value.
static String
join(CharSequence
8 It returns a joined string.
delimiter, CharSequence...
elements)
static String
join(CharSequence
9 delimiter, Iterable<? It returns a joined string.
extends CharSequence>
elements)
It checks the equality of
boolean equals(Object
10 string with the given
another)
object.
11 boolean isEmpty() It checks if string is empty.
It concatenates the
12 String concat(String str)
specified string.
String replace(char old, It replaces all occurrences
13
char new) of the specified char value.
String It replaces all occurrences
14 replace(CharSequence of the specified
old, CharSequence new) CharSequence.
static String It compares another
15 equalsIgnoreCase(String string. It doesn't check
another) case.
It returns a split string
16 String[] split(String regex)
matching regex.
String[] split(String regex, It returns a split string
17
int limit) matching regex and limit.
It returns an interned
18 String intern()
string.
It returns the specified
19 int indexOf(int ch)
char value index.
It returns the specified
int indexOf(int ch, int
20 char value index starting
fromIndex)
with given index.
int indexOf(String It returns the specified
21
substring) substring index.
It returns the specified
int indexOf(String
22 substring index starting
substring, int fromIndex)
with given index.
It returns a string in
23 String toLowerCase()
lowercase.
It returns a string in
String
24 lowercase using specified
toLowerCase(Locale l)
locale.
It returns a string in
25 String toUpperCase()
uppercase.
It returns a string in
String
26 uppercase using specified
toUpperCase(Locale l)
locale.
It removes beginning and
27 String trim() ending spaces of this
string.
It converts given type into
static String valueOf(int
28 string. It is an overloaded
value)
method.
What will we learn in String Handling?
o Concept of String
o Immutable String
o String Comparison
o String Concatenation
o Concept of Substring
o String class methods and its usage
o StringBuffer class
o StringBuilder class
o Creating Immutable class
o toString() method
o StringTokenizer class
o Immutable String in Java
o A String is an unavoidable type of variable while writing any application
program. String references are used to store various attributes like
username, password, etc. In Java, String objects are immutable.
Immutable simply means unmodifiable or unchangeable.
1. Once String object is created its data or state can't be changed but a
new
2. class Testimmutablestring{
3. public static void main(String args[]){
4. String s="Sachin";
5. [Link](" Tendulkar");//concat() method appends the string at the
end
6. [Link](s);//will print Sachin because strings are immuta
ble objects
7. }
8. }
o String object is created.
o Why String objects are immutable in Java?
o As Java uses the concept of String literal. Suppose there are 5 reference
variables, all refer to one object "Sachin". If one reference variable
changes the value of the object, it will be affected by all the reference
variables. That is why String objects are immutable in Java.
o Following are some features of String which makes String objects
immutable.
o 1. ClassLoader:
o A ClassLoader in Java uses a String object as an argument. Consider, if
the String object is modifiable, the value might be changed and the class
that is supposed to be loaded might be different.
o To avoid this kind of misinterpretation, String is immutable.
o 2. Thread Safe:
o As the String object is immutable we don't have to take care of the
synchronization that is required while sharing an object across multiple
threads.
o 3. Security:
o As we have seen in class loading, immutable String objects avoid further
errors by loading the correct class. This leads to making the application
program more secure. Consider an example of banking software. The
username and password cannot be modified by any intruder because
String objects are immutable. This can make the application program
more secure.
o 4. Heap space
The immutability of String helps to minimize the usage in the heap
memory. When we try to declare a new String object, the JVM checks
whether the value already exists in the String pool or not. If it exists, the
same value is assigned to the new object. This feature allows Java to use
the heap space efficiently.
Why String class is Final in Java?
The reason behind the String class being final is because no one can override
the methods of the String class. So that it can provide the same features to the
new String objects as well as to the old ones.
String function ----
1) compare(),
2) concat(),
3) equals(),
4) split(),
5) length(),
6) replace(),
7) compareTo(),
8) intern(),
9) substring()
1) compare();
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. [Link]([Link](s2));//true
8. [Link]([Link](s3));//true
9. [Link]([Link](s4));//false
10. }
11. }
true
true
false
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. [Link]([Link](s2));//false
7. [Link]([Link](s2));//true
8. }
9. }
false
true
2) By Using == operator
The == operator compares references not values.
[Link]
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. [Link](s1==s2);//true (because both refer to same instan
ce)
7. [Link](s1==s3);//false(because s3 refers to instance creat
ed in nonpool)
8. }
9. }
Test it Now
Output:
true
false
3) String compare by compareTo() method
The above code, demonstrates the use of == operator used for comparing
two String objects.
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically and
returns an integer value that describes if first string is less than, equal to or
greater than second string.
Suppose s1 and s2 are two String objects. If:
o s1 == s2 : The method returns 0.
o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.
[Link]
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. [Link]([Link](s2));//0
7. [Link]([Link](s3));//1(because s1>s3)
8. [Link]([Link](s1));//-1(because s3 < s1 )
9. }
10. }
Test it Now
Output:
0
1
-1
2) concat(); (public String concat(String another)
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. [Link](s);//Sachin Tendulkar
5. }
6. }
Sachin Tendulkar
1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. [Link](s);//80Sachin4040
5. }
6. }
80Sachin4040
1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=[Link](s2);
6. [Link](s3);//Sachin Tendulkar
7. }
8. }
Sachin Tendulkar
3) substring();
9. String s="hello";
10. [Link]([Link](0,2)); //returns he as a substring
1. public class TestSubstring{
2. public static void main(String args[]){
3. String s="SachinTendulkar";
4. [Link]("Original String: " + s);
5. [Link]("Substring starting from index 6: " +[Link](6))
;//Tendulkar
6. [Link]("Substring starting from index 0 to 6: "+[Link]
g(0,6)); //Sachin
7. }
8. }
Original String: SachinTendulkar
Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin
3. Spilt;
4. import [Link].*;
5.
6. public class TestSubstring2
7. {
8. /* Driver Code */
9. public static void main(String args[])
10. {
11. String text= new String("Hello, My name is Sachin");
12. /* Splits the sentence by the delimeter passed as an argument */
13. String[] sentences = [Link]("\\.");
14. [Link]([Link](sentences));
15. }
16. }
Output:
[Hello, My name is Sachin]
4. length;
1. public class Stringoperation5
2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. [Link]([Link]());//6
7. }
8. }
5. intern();
1. public class Stringoperation6
2. {
3. public static void main(String ar[])
4. {
5. String s=new String("Sachin");
6. String s2=[Link]();
7. [Link](s2);//Sachin
8. }
9. }
Sachin
Java String replace() Method
The String class replace() method replaces all occurrence of first sequence of
character with second sequence of character.
[Link]
1. public class Stringoperation8
2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is
an Island.";
6. String replaceString=[Link]("Java","Kava");//replaces all occurrenc
es of "Java" to "Kava"
7. [Link](replaceString);
8. }
9. }
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Interfaces and Classes in Strings in Java
CharBuffer: This class implements the CharSequence interface. This class
is used to allow character buffers to be used in place of CharSequences.
An example of such usage is the regular-expression package
[Link].
String: It is a sequence of characters. In Java, objects of String are
immutable which means a constant and cannot be changed once created.
harSequence Interface
CharSequence Interface is used for representing the sequence of
Characters in Java.
Classes that are implemented using the CharSequence interface are
mentioned below and these provides much of functionality like substring,
lastoccurence, first occurence, concatenate , toupper, tolower etc.
1. String
2. StringBuffer
3. StringBuilder
1. String
String is an immutable class which means a constant and cannot be
changed once created and if wish to change , we need to create an new
object and even the functionality it provides like toupper, tolower, etc all
these return a new object , its not modify the original object. It is
automatically thread safe.
Syntax
String str= "geeks";
or
String str= new String("geeks")
2. StringBuffer
StringBuffer is a peer class of String, it is mutable in nature and it is thread
safe class , we can use it when we have multi threaded environment and
shared object of string buffer i.e, used by mutiple thread. As it is thread
safe so there is extra overhead, so it is mainly used for multithreaded
program.
Syntax:
StringBuffer demoString = new StringBuffer("GeeksforGeeks");
3. StringBuilder
StringBuilder in Java represents an alternative to String and StringBuffer
Class, as it creates a mutable sequence of characters and it is not thread
safe. It is used only within the thread , so there is no extra overhead , so it
is mainly used for single threaded program.
Syntax:
StringBuilder demoString = new StringBuilder();
[Link]("GFG");
Difference between String and
StringBuffer
There are many differences between String and StringBuffer. A list of
differences between String and StringBuffer are given below:
No. String StringBuffer
The String class is The StringBuffer class is
1)
immutable. mutable.
String is slow and
2) StringBuffer is fast and
consumes more memory
consumes less memory
when we concatenate too
many strings because when we concatenate t
every time it creates new strings.
instance.
String class overrides the
equals() method of Object
StringBuffer class doesn't
class. So you can compare
3) override the equals()
the contents of two
method of Object class.
strings by equals()
method.
String class is slower while StringBuffer class is faster
4) performing concatenation while performing
operation. concatenation operation.
String class uses String StringBuffer uses Heap
5)
constant pool. memory
…………………………………………………………………………………………………………………………………..
-----------------VECTOR------------------
Java Vector;
Vector is like the dynamic array which can grow or shrink its size. Unlike array,
we can store n-number of elements in it as there is no size limit. It is a part of
Java Collection framework since Java 1.2. It is found in the [Link] package
and implements the List interface, so we can use all the methods of List
interface here.
It is recommended to use the Vector class in the thread-safe implementation
only. If you don't need to use the thread-safe implementation, you should use
the ArrayList, the ArrayList will perform better in such case.
It is similar to the ArrayList, but with two differences-
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a
collections framework.
Java Vector class Declaration
1. public class Vector<E>
2. extends Object<E>
3. implements List<E>, Cloneable, Serializable
Java Vector Constructors
Vector class supports four types of constructors. These are given below:
SN Constructor Description
It constructs an empty
1) vector() vector with the default
size as 10.
2) vector(int initialCapacity) It constructs an empty
vector with the specified
initial capacity and with its
capacity increment equal
to zero.
It constructs an empty
vector(int initialCapacity, vector with the specified
3)
int capacityIncrement) initial capacity and
capacity increment.
It constructs a vector that
Vector( Collection<?
4) contains the elements of a
extends E> c)
collection c.
Java Vector Methods
The following are the list of Vector class methods:
SN Method Description
It is used to append the
1) add() specified element in the
given vector.
It is used to append all of
the elements in the
2) addAll()
specified collection to the
end of this Vector.
It is used to append the
specified component to
3) addElement() the end of this vector. It
increases the vector size
by one.
It is used to get the
4) capacity() current capacity of this
vector.
It is used to delete all of
5) clear() the elements from this
vector.
It returns a clone of this
6) clone()
vector.
It returns true if the vector
7) contains() contains the specified
element.
It returns true if the vector
contains all of the
8) containsAll()
elements in the specified
collection.
It is used to copy the
9) copyInto() components of the vector
into the specified array.
It is used to get the
10) elementAt() component at the
specified index.
It returns an enumeration
11) elements() of the components of a
vector.
It is used to increase the
capacity of the vector
which is in use, if
necessary. It ensures that
12) ensureCapacity() the vector can hold at
least the number of
components specified by
the minimum capacity
argument.
It is used to compare the
13) equals() specified object with the
vector for equality.
It is used to get the first
14) firstElement()
component of the vector.
It is used to perform the
given action for each
element of the Iterable
15) forEach() until all elements have
been processed or the
action throws an
exception.
It is used to get an
16) get() element at the specified
position in the vector.
It is used to get the hash
17) hashCode()
code value of a vector.
It is used to get the index
of the first occurrence of
the specified element in
18) indexOf()
the vector. It returns -1 if
the vector does not
contain the element.
It is used to insert the
specified object as a
19) insertElementAt() component in the given
vector at the specified
index.
It is used to check if this
20) isEmpty() vector has no
components.
It is used to get an iterator
21) iterator() over the elements in the
list in proper sequence.
It is used to get the last
22) lastElement()
component of the vector.
It is used to get the index
of the last occurrence of
the specified element in
23) lastIndexOf()
the vector. It returns -1 if
the vector does not
contain the element.
It is used to get a list
iterator over the elements
24) listIterator()
in the list in proper
sequence.
It is used to remove the
specified element from
25) remove() the vector. If the vector
does not contain the
element, it is unchanged.
It is used to delete all the
elements from the vector
26) removeAll()
that are present in the
specified collection.
It is used to remove all
elements from the vector
27) removeAllElements()
and set the size of the
vector to zero.
It is used to remove the
first (lowest-indexed)
28) removeElement()
occurrence of the
argument from the vector.
It is used to delete the
29) removeElementAt() component at the
specified index.
It is used to remove all of
the elements of the
30) removeIf()
collection that satisfy the
given predicate.
It is used to delete all of
the elements from the
vector whose index is
31) removeRange()
between fromIndex,
inclusive and toIndex,
exclusive.
It is used to replace each
element of the list with
32) replaceAll()
the result of applying the
operator to that element.
It is used to retain only
that element in the vector
33) retainAll()
which is contained in the
specified collection.
It is used to replace the
element at the specified
34) set()
position in the vector with
the specified element.
It is used to set the
component at the
35) setElementAt() specified index of the
vector to the specified
object.
It is used to set the size of
36) setSize()
the given vector.
It is used to get the
37) size() number of components in
the given vector.
It is used to sort the list
according to the order
38) sort()
induced by the specified
Comparator.
It is used to create a late-
binding and fail-fast
39) spliterator()
Spliterator over the
elements in the list.
It is used to get a view of
the portion of the list
40) subList() between fromIndex,
inclusive, and toIndex,
exclusive.
It is used to get an array
containing all of the
41) toArray()
elements in this vector in
correct order.
It is used to get a string
42) toString() representation of the
vector.
It is used to trim the
43) trimToSize() capacity of the vector to
the vector's current size.
Java Vector Example
1. import [Link].*;
2. public class VectorExample {
3. public static void main(String args[]) {
4. //Create a vector
5. Vector<String> vec = new Vector<String>();
6. //Adding elements using add() method of List
7. [Link]("Tiger");
8. [Link]("Lion");
9. [Link]("Dog");
10. [Link]("Elephant");
11. //Adding elements using addElement() method of Vector
12. [Link]("Rat");
13. [Link]("Cat");
14. [Link]("Deer");
15.
16. [Link]("Elements are: "+vec);
17. }
18. }
Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Java Vector Example 2
1. import [Link].*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. [Link]("Tiger");
8. [Link]("Lion");
9. [Link]("Dog");
10. [Link]("Elephant");
11. //Check size and capacity
12. [Link]("Size is: "+[Link]());
13. [Link]("Default capacity is: "+[Link]());
14. //Display Vector elements
15. [Link]("Vector element is: "+vec);
16. [Link]("Rat");
17. [Link]("Cat");
18. [Link]("Deer");
19. //Again check size and capacity after two insertions
20. [Link]("Size after addition: "+[Link]());
21. [Link]("Capacity after addition is: "+[Link]());
22. //Display Vector elements again
23. [Link]("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if([Link]("Tiger"))
26. {
27. [Link]("Tiger is present at the index " +[Link]
Of("Tiger"));
28. }
29. else
30. {
31. [Link]("Tiger is not present in the list.");
32. }
33. //Get the first element
34. [Link]("The first animal of the vector is = "+[Link]
lement());
35. //Get the last element
36. [Link]("The last animal of the vector is = "+[Link]
ement());
37. }
38. }
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
Java Vector Example 3
1. import [Link].*;
2. public class VectorExample2 {
3. public static void main(String args[]) {
4. //Create an empty Vector
5. Vector<Integer> in = new Vector<>();
6. //Add elements in the vector
7. [Link](100);
8. [Link](200);
9. [Link](300);
10. [Link](200);
11. [Link](400);
12. [Link](500);
13. [Link](600);
14. [Link](700);
15. //Display the vector elements
16. [Link]("Values in vector: " +in);
17. //use remove() method to delete the first occurence of an eleme
nt
18. [Link]("Remove first occourence of element 200: "+i
[Link]((Integer)200));
19. //Display the vector elements afre remove() method
20. [Link]("Values in vector: " +in);
21. //Remove the element at index 4
22. [Link]("Remove element at index 4: " +[Link](4));
23. [Link]("New Value list in vector: " +in);
24. //Remove an element
25. [Link](5);
26. //Checking vector and displays the element
27. [Link]("Vector element after removal: " +in);
28. //Get the hashcode for this vector
29. [Link]("Hash code of this vector = "+[Link]());
30. //Get the element at specified index
31. [Link]("Element at index 1 is = "+[Link](1));
32. }
33. }
Output:
Values in vector: [100, 200, 300, 200, 400, 500, 600, 700]
Remove first occourence of element 200: true
Values in vector: [100, 300, 200, 400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300, 200, 400, 600, 700]
Vector element after removal: [100, 300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300
import [Link];
public class VectorExample {
public static void main(String[] args) {
// Create a new vector
Vector<Integer> v = new Vector<>(3, 2);
// Add elements to the vector
[Link](1);
[Link](2);
[Link](3);
// Insert an element at index 1
[Link](0, 1);
// Remove the element at index 2
[Link](2);
// Print the elements of the vector
for (int i : v) {
[Link](i);
}
}
}
Output
1
0
3
Performing Various Operations on Vector class in Java
Let us discuss various operations on Vector class that are listed as follows:
• Adding elements
• Updating elements
• Removing elements
• Iterating over elements
Operation 1: Adding Elements
In order to add the elements to the Vector, we use the add() method. This
method is overloaded to perform multiple operations based on different
parameters. They are listed below as follows:
• add(Object): This method is used to add an element at the end
of the Vector.
• add(int index, Object): This method is used to add an element
at a specific index in the Vector.
Example:
Java
// Java Program to Add Elements in Vector Class
// Importing required classes
import [Link].*;
import [Link].*;
// Main class
// AddElementsToVector
class GFG {
// Main driver method
public static void main(String[] arg)
{
// Case 1
// Creating a default vector
Vector v1 = new Vector();
// Adding custom elements
// using add() method
[Link](1);
[Link](2);
[Link]("geeks");
[Link]("forGeeks");
[Link](3);
// Printing the vector elements to the console
[Link]("Vector v1 is " + v1);
// Case 2
// Creating generic vector
Vector<Integer> v2 = new Vector<Integer>();
// Adding custom elements
// using add() method
[Link](1);
[Link](2);
[Link](3);
// Printing the vector elements to the console
[Link]("Vector v2 is " + v2);
}
}
Output
Vector v1 is [1, 2, geeks, forGeeks, 3]
Vector v2 is [1, 2, 3]
Output:
Operation 2: Updating Elements
After adding the elements, if we wish to change the element, it can be done using
the set() method. Since a Vector is indexed, the element which we wish to change is
referenced by the index of the element. Therefore, this method takes an index and
the updated element to be inserted at that index.
Example:
Java
// Java code to change the
// elements in vector class
import [Link].*;
// Driver Class
public class UpdatingVector {
// Main Function
public static void main(String args[])
{
// Creating an empty Vector
Vector<Integer> vec_tor = new Vector<Integer>();
// Use add() method to add elements in the vector
vec_tor.add(12);
vec_tor.add(23);
vec_tor.add(22);
vec_tor.add(10);
vec_tor.add(20);
// Displaying the Vector
[Link]("Vector: " + vec_tor);
// Using set() method to replace 12 with 21
[Link]("The Object that is replaced is: "
+ vec_tor.set(0, 21));
// Using set() method to replace 20 with 50
[Link]("The Object that is replaced is: "
+ vec_tor.set(4, 50));
// Displaying the modified vector
[Link]("The new Vector is:" + vec_tor);
}
}
Output
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]
Operation 3: Removing Elements
In order to remove an element from a Vector, we can use the remove() method. This
method is overloaded to perform multiple operations based on different parameters.
They are:
• remove(Object): This method is used to remove an object from the
Vector. If there are multiple such objects, then the first occurrence of the
object is removed.
• remove(int index): Since a Vector is indexed, this method takes an
integer value which simply removes the element present at that specific
index in the Vector. After removing the element, all the elements are
moved to the left to fill the space and the indices of the objects are
updated.
Example:
Java
// Java code illustrating the removal
// of elements from vector
import [Link].*;
import [Link].*;
class RemovingElementsFromVector {
public static void main(String[] arg)
{
// Create default vector of capacity 10
Vector v = new Vector();
// Add elements using add() method
[Link](1);
[Link](2);
[Link]("Geeks");
[Link]("forGeeks");
[Link](4);
// Removing first occurrence element at 1
[Link](1);
// Checking vector
[Link]("after removal: " + v);
}
}
Output
after removal: [1, Geeks, forGeeks, 4]
Operation 4: Iterating the Vector
There are multiple ways to iterate through the Vector. The most famous
ways are by using the basic for loop in combination with a get() method to
get the element at a specific index and the advanced for a loop.
Example:
Java
// Java program to iterate the elements
// in a Vector
import [Link].*;
public class IteratingVector {
public static void main(String args[])
{
// create an instance of vector
Vector<String> v = new Vector<>();
// Add elements using add() method
[Link]("Geeks");
[Link]("Geeks");
[Link](1, "For");
// Using the Get method and the
// for loop
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i) + " ");
}
[Link]();
// Using the for each loop
for (String str : v)
[Link](str + " ");
}
}
Output
Geeks For Geeks
Geeks For Geeks
Exception Handling in Java
1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur
The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that the normal flow of the application can be
maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of
the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10
will not be executed. However, when we perform exception handling, the rest
of the statements will be executed. That is why we use exception handling
in Java.
Hierarchy of Java Exception classes
The [Link] class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there
are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description
The "try" keyword is used to specify a
block where we should place an
try exception code. It means we can't use
try block alone. The try block must be
followed by either catch or finally.
The "catch" block is used to handle the
exception. It must be preceded by try
catch block which means we can't use catch
block alone. It can be followed by finally
block later.
The "finally" block is used to execute the
necessary code of the program. It is
finally
executed whether an exception is
handled or not.
The "throw" keyword is used to throw an
throw
exception.
The "throws" keyword is used to declare
exceptions. It specifies that there may
throws occur an exception in the method. It
doesn't throw an exception. It is always
used with method signature.
Java Exception Handling Example
Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.
[Link]
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){[Link](e);}
7. //rest code of the program
8. [Link]("rest of the code...");
9. }
10. }
Test it Now
Output:
Exception in thread main [Link]:/ by zero
rest of the code...
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of
the block code will not execute. So, it is recommended not to keep the code in
try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw an exception
3. }finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the parent
class exception ( i.e., Exception) or the generated exception type. However, the
good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple
catch block with a single try block.
Internal Working of Java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception
occurred).
o Causes the program to terminate.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Example 1
[Link]
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. [Link]("rest of the code");
8.
9. }
10.
11. }
12. Java Catch Multiple Exceptions
13. Java Multi-catch block
14. A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-
catch block.
15. At a time only one exception occurs and at a time only one catch block
is executed.
16. All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.
Example 1
Let's see a simple example of java multi-catch block.
[Link]
1. public class MultipleCatchBlock1 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. [Link]("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. [Link]("ArrayIndexOutOfBounds Exception oc
curs");
16. }
17. catch(Exception e)
18. {
19. [Link]("Parent Exception occurs");
20. }
21. [Link]("rest of the code");
22. }
23. }
Test it Now
Output:
Arithmetic Exception occurs
rest of the code
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try block. Every
statement that we enter a statement in try block, context of that exception is pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
Java Nested try Example
Example 1
Let's see an example where we place a try block within another try block for two different
exceptions.
1. public class NestedTryBlock{
2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. [Link]("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. [Link](e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. [Link](e);
29. }
30.
31.
32. [Link]("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. [Link]("handled the exception (outer catch)");
38. }
39.
40. [Link]("normal flow..");
41. }
42. }
Output:
java finally block
Java finally block is a block used to execute important code such as closing
the connection, etc.
Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.
The finally block follows the try-catch block.
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing
a file, closing connection, etc.
o The important statements to be printed can be placed in the finally
block.
o Java throw Exception
o In Java, exceptions allows us to write good quality codes where the errors
are checked at the compile time instead of runtime and we can create
custom exceptions making the code recovery and debugging easier.
o Java throw keyword
o The Java throw keyword is used to throw an exception explicitly.
o We specify the exception object which is to be thrown. The Exception
has some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.
o We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception. We will discuss
custom exceptions later in this section.
We can also define our own set of conditions and throw an exception explicitly
using throw keyword. For example, we can throw ArithmeticException if we
divide a number by another number. Here, we just need to set the condition
and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
1. throw new exception_class("error message");
Let's see the example of throw IOException.
1. throw new IOException("sorry device error");
2. ublic class TestThrow1 {
3. //function to check if person is eligible to vote or not
4. public static void validate(int age) {
5. if(age<18) {
6. //throw Arithmetic exception if not eligible to vote
7. throw new ArithmeticException("Person is not eligible to vote
");
8. }
9. else {
10. [Link]("Person is eligible to vote!!");
11. }
12. }
13. //main method
14. public static void main(String args[]){
15. //calling the function
16. validate(13);
17. [Link]("rest of the code...");
18. }
19. }
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code
before it being used.
Syntax of Java throws
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
Which exception should be declared?
Ans: Checked exception only, because:
o unchecked exception: under our control so we can correct our code.
o error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
Java throws Example
Let's see the example of Java throws clause which describes that checked
exceptions can be propagated by throws keyword.
[Link]
1. import [Link];
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){[Link]("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. [Link]("normal flow...");
18. }
19. }
Test it Now
Output:
exception handled
normal flow...
Difference between throw and throws in
Java
The throw and throws is the concept of exception handling where the throw keyword throw the
exception explicitly from a method or a block of code whereas the throws keyword is used in
signature of the method.
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
Sr. no. Basis of Differences throw throws
Java throws keyword is
Java throw keyword is used in the method
used throw an exception signature to declare an
1. Definition explicitly in the code, exception which might
inside the function or be thrown by the
the block of code. function while the
execution of the code.
Type of exception Using throws keyword,
Using throw keyword, we can declare both
we can only propagate checked and unchecked
unchecked exception exceptions. However,
2. Usage
i.e., the checked the throws keyword can
exception cannot be be used to propagate
propagated using throw checked exceptions
only. only.
The throw keyword is The throws keyword is
followed by an instance followed by class
3. Syntax
of Exception to be names of Exceptions to
thrown. be thrown.
throw is used within the throws is used with the
4. Declaration
method. method signature.
We can declare multiple
We are allowed to exceptions using throws
throw only one keyword that can be
5. Internal implementation exception at a time i.e. thrown by the method.
we cannot throw For example, main()
multiple exceptions. throws IOException,
SQLException.
Java throw Example
[Link]
1. public class TestThrow {
2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate squa
re");
6. }
7. else {
8. [Link]("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. [Link](-3);
15. [Link]("Rest of the code..");
16. }
17. }
Output:
Advertisement
Java throws Example
[Link]
1. public class TestThrows {
2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticExcepti
on {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. [Link]([Link](45, 0));
12. }
13. catch (ArithmeticException e){
14. [Link]("\nNumber cannot be divided by 0");
15. }
16.
17. [Link]("Rest of the code..");
18. }
19. }
---------------------------OOP’S CONCEPT -----------------
Q-) What is object oriented programming?
ANS-) Solving a problem by creating objects is one of
the most popular approaches in programming this is
Called object oriented programming.
Q-) What is dry?
Stands for do not repeat yourself.
As the name suggests, Object-Oriented Programming or Java
OOPs concept refers to languages that use objects in programming, they
use objects as a primary source to implement what is to happen in the
code. Objects are seen by the viewer or user, performing tasks you
assign.
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
Access Modifiers;
in Java, Access modifiers help to restrict the scope of a class, constructor,
variable, method, or data member. It provides security, accessibility, etc to
the user depending upon the access modifier used with the element. Let
us learn about Java Access Modifiers, their types, and the uses of access
modifiers
Types of Access Modifiers in Java
There are four types of access modifiers available
in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data member
– It is said to be having the default access modifier by default. The data
members, classes, or methods that are not declared using any access
modifiers i.e. having default access modifiers are accessible only within
the same package.
In this example, we will create two packages and the classes in the
packages will be having the default access modifiers and we will try to
access a class from one package from a class of the second package.
// Java program to illustrate default modifier
package p1;
// Class Geek is having Default access modifier
class Geek
{
void display()
{
[Link]("Hello World!");
}
}
2. Private Access Modifier
The private access modifier is specified using the
keyword private. The methods or data members
declared as private are accessible only within the
class in which they are declared.
Any other class of the same package will not be
able to access these members.
Top-level classes or interfaces can not be declared
as private because
private means “only visible within the enclosing
class”.
protected means “only visible within the enclosing
class and any subclasses”
Hence these modifiers in terms of application to
classes, apply only to nested classes and not on
top-level classes
In this example, we will create two classes A and B
within the same package p1. We will declare a
method in class A as private and try to access this
method from class B and see the result.
// Java program to illustrate error while
// Using class from different package with
// Private Modifier
package p1;
// Class A
class A {
private void display()
{
[Link]("GeeksforGeeks");
}
}
// Class B
class B {
public static void main(String args[])
{
A obj = new A();
// Trying to access private method
// of another class
[Link]();
}
}
Output:
error: display() has private access in A
[Link]();
3. Protected Access Modifier
The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible
within the same package or subclasses in different packages.
In this example, we will create two packages p1 and p2. Class A in p1 is
made public, to access it in p2. The method display in class A is protected
and class B is inherited from class A and this protected method is then
accessed by creating an object of class B.
// Java Program to Illustrate
// Protected Modifier
package p1;
// Class A
public class A {
protected void display()
{
[Link]("GeeksforGeeks");
}
}
Public Access modifier
The public access modifier is specified using the keyword public.
• The public access modifier has the widest scope among all
other access modifiers.
• Classes, methods, or data members that are declared as public
are accessible from everywhere in the program. There is no
restriction on the scope of public data members.
1. Private: The access level of a private modifier is only within the class.
It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do
not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.
5. Understanding Java Access Modifiers
6. Let's understand the access modifiers in Java by a simple table.
Access within class within outside outside
Modifier package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Getter and Setter in Java
In Java, Getter and Setter are methods used to
protect your data and make your code more
secure. Getter and Setter make the programmer
convenient in setting and getting the value for a
particular data type.
Getter in Java: Getter returns the value
(accessors), it returns the value of data type int,
String, double, float, etc. For the program’s
convenience, the getter starts with the word “get”
followed by the variable name.
Setter in Java: While Setter sets or updates the
value (mutators). It sets the value for any variable
used in a class’s programs. and starts with the
word “set” followed by the variable name.
Syntax
class ABC{
private variable;
public void setVariable(int x){
[Link]=x;
}
public int getVariable{
return variable;
}
}
Examples of Getter and Setter in Java
Example 1:
Java
// Java Program to Illustrate Getter and Setter
// Importing input output classes
import [Link].*;
// Class 1
// Helper class
class GetSet {
// Member variable of this class
private String name;
// Method 1 - Getter
public String getName() { return name; }
// Method 2 - Setter
public void setName(String N)
{
// This keyword refers to current instance itself
[Link] = N;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of class 1 in main() method
GetSet obj = new GetSet();
// Setting the name by calling setter method
[Link]("dhruv");
// Getting the name by calling getter method
[Link]([Link]());
}
}
Output
dhruv
oops concept –
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in
Object-Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
What is 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:
1. Modifiers: A class can be public or have default access (Refer
to this for details).
2. Class name: The class name should begin with the initial letter
capitalized by convention.
3. 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.
4. 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.
5. Body: The class body is surrounded by braces, { }.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.
What is Object?
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:
1. State: It is represented by the attributes of an object. It also
reflects the properties of an object.
2. Behavior: It is represented by the methods of an object. It also
reflects the response of an object to other objects.
3. Identity: It is a unique name given to an object that enables it to
interact with other objects.
4. Method: A method is a collection of statements that perform
some specific task and return the result to the caller. A method
can perform some specific task without returning anything.
Methods allow us to reuse the code without retyping it, which is
why they are considered time savers. In Java, every method
must be part of some class, which is different from languages
like C, C++, and Python.
Object
Any entity that has state and behavior is known as an object. For example, a
chair, pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an
address and takes up some space in memory. Objects can communicate
without knowing the details of each other's data or code. The only necessary
thing is the type of message accepted and the type of response returned by
the objects.
Example: A dog is an object because it has states like color, name, breed, etc.
as well as behaviors like wagging the tail, barking, eating, etc.
Class and Objects one Simple Java Program:
Java
public class GFG {
static String Employee_name;
static float Employee_salary;
static void set(String n, float p) {
Employee_name = n;
Employee_salary = p;
}
static void get() {
[Link]("Employee name is: " +Employee_name );
[Link]("Employee CTC is: " + Employee_salary);
}
public static void main(String args[]) {
[Link]("Rathod Avinash", 10000.0f);
[Link]();
}
}
Output
Employee name is: Rathod Avinash
Employee CTC is: 10000.0
bstraction
Data Abstraction is the property by virtue of which
only the essential details are displayed to the user.
The trivial or non-essential units are not displayed
to the user. Ex: A car is viewed as a car rather than
its individual components.
Data Abstraction may also be defined as the
process of identifying only the required
characteristics of an object, ignoring the irrelevant
details. The properties and behaviors of an object
differentiate it from other objects of similar type
and also help in classifying/grouping the object.
Consider a real-life example of a man driving a car.
The man only knows that pressing the
accelerators will increase the car speed or
applying brakes will stop the car, but he does not
know how on pressing the accelerator, the speed
is actually increasing. He does not know about the
inner mechanism of the car or the
implementation of the accelerators, brakes etc. in
the car. This is what abstraction is.
In Java, abstraction is achieved by interfaces and
abstract classes. We can achieve 100% abstraction
using interfaces.
The abstract method contains only method
declaration but not implementation
//abstract class
abstract class GFG{
//abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing.
Encapsulation
It is defined as the wrapping up of data under a
single unit. It is the mechanism that binds
together the code and the data it manipulates.
Another way to think about encapsulation is that
it is a protective shield that prevents the data
from being accessed by the code outside this
shield.
Technically, in encapsulation, the variables or the
data in a class is hidden from any other class and
can be accessed only through any member
function of the class in which they are declared.
In encapsulation, the data in a class is hidden from
other classes, which is similar to what data-hiding
does. So, the terms “encapsulation” and “data-
hiding” are used interchangeably.
Encapsulation can be achieved by declaring all the
variables in a class as private and writing public
methods in the class to set and get the values of
the variables.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
//Encapsulation using private modifier
//Employee class contains private data called employee id and employee name
class Employee {
private int empid;
private String ename;
}
Polymorphism in Java
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.
What is Polymorphism in Java?
Polymorphism is considered one of the important features of Object-
Oriented Programming. Polymorphism allows us to perform a single
action in different ways. In other words, polymorphism allows you to
define one interface and have multiple implementations. The word “poly”
means many and “morphs” means forms, So it means many forms.
Types of Java Polymorphism
In Java Polymorphism is mainly divided into two types:
• 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.
Note: But Java doesn’t support the 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.
// Java Program for Method overloading
// By using Different Types of Arguments
// Class 1
// Helper class
class Helper {
// Method with 2 integer parameters
static int Multiply(int a, int b)
// Returns product of integer numbers
return a * b;
// 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 GFG {
// Main driver method
public static void main(String[] args)
// Calling method by passing
// input as in arguments
[Link]([Link](2, 4));
[Link]([Link](5.5, 6.3));
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.
Example
Java
// Java Program for Method Overriding
// Class 1
// Helper class
class Parent {
// Method of parent class
void Print()
{
// Print statement
[Link]("parent class");
}
}
// Class 2
// Helper class
class subclass1 extends Parent {
// Method
void Print() { [Link]("subclass1"); }
}
// Class 3
// Helper class
class subclass2 extends Parent {
// Method
void Print()
{
// Print statement
[Link]("subclass2");
}
}
// Class 4
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of class 1
Parent a;
// Now we will be calling print methods
// inside main() method
a = new subclass1();
[Link]();
a = new subclass2();
[Link]();
}
}
Output
subclass1
subclass2
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through
interface only. We will learn about interfaces later.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. [Link]();
11. [Link]();
12. }}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As
you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){[Link]("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. [Link]();
14. [Link]();
15. [Link]();
16. }}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance.
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){[Link]("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. [Link]();
14. [Link]();
15. //[Link]();//[Link]
16. }}
Output:
meowing...
eating...
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java
1. class A{
2. void msg(){[Link]("Hello");}
3. }
4. class B{
5. void msg(){[Link]("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. [Link]();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error
Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. 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 [Link].*;
import [Link].*;
import [Link].*;
// Parent class
class One {
public void print_geek()
{
[Link]("Geeks");
}
}
class Two extends One {
public void print_for() { [Link]("for"); }
}
// 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
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.
// Importing required libraries
import [Link].*;
import [Link].*;
import [Link].*;
// Parent class One
class One {
// Method to print "Geeks"
public void print_geek() {
[Link]("Geeks");
}
}
// Child class Two inherits from class One
class Two extends One {
// Method to print "for"
public void print_for() {
[Link]("for");
}
}
// Child class Three inherits from class Two
class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
[Link]("Geeks");
}
}
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
// Calling method from class One
g.print_geek();
// Calling method from class Two
g.print_for();
// Calling method from class Three
g.print_lastgeek();
}
}
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.
// Java program to illustrate the
// concept of Hierarchical inheritance
class A {
public void print_A() { [Link]("Class A"); }
}
class B extends A {
public void print_B() { [Link]("Class B"); }
}
class C extends A {
public void print_C() { [Link]("Class C"); }
}
class D extends A {
public void print_D() { [Link]("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();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();
D obj_D = new D();
obj_D.print_A();
obj_D.print_D();
}
}
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.
// Java program to illustrate the
// concept of Multiple inheritance
import [Link].*;
import [Link].*;
import [Link].*;
interface One {
public void print_geek();
}
interface Two {
public void print_for();
}
interface Three extends One, Two {
public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
[Link]("Geeks");
}
public void print_for() { [Link]("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.
Java IS-A type of Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how
the extends keyword is used to achieve inheritance.
Java
public class SolarSystem {
}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}
Interfaces in Java
Last INTERFACE
An ••Interface in Java programming language is defined as an abstract type
used to specify the behavior of a class. An interface in Java is a blueprint of a
behavior. A Java interface contains static constants and abstract methods.
What are Interfaces in Java?
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 inheritances 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.
Uses of Interfaces in Java
Uses of Interfaces in Java are mentioned below:
• It is used to achieve total abstraction.
• Since java does not support multiple
inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
• Any class can extend only 1 class, but can any
class implement an infinite number of
interfaces.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction.
• Difference Between Class and Interface
• Although Class and Interface seem the same there have certain
differences between Classes and Interface. The major differences
between a class and an interface are mentioned below:
Class Interface
In an interface, you must initialize
In class, you can instantiate
variables as they are final but you
variables and create an object.
can’t create an object.
A class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods.
The access specifiers used with
In Interface only one specifier is
classes are private, protected, and
used- Public.
public.
• Implementation: To implement an interface, we use the
keyword implements
• Java
• // Java program to demonstrate working of
• // interface
•
• import [Link].*;
•
• // A simple interface
• interface In1 {
•
• // public, static and final
• final int a = 10;
•
• // public and abstract
• void display();
• }
•
• // A class that implements the interface.
• class TestClass implements In1 {
•
• // Implementing the capabilities of
• // interface.
• public void display(){
• [Link]("Geek");
• }
•
• // Driver Code
• public static void main(String[] args)
• {
• TestClass t = new TestClass();
• [Link]();
• [Link](t.a);
• }
• }
Constructors in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value?
4. Copying the values of one object into another
5. Does constructor perform other tasks instead of the initialization
In Java, a constructor is a block of codes similar to the method. It is called when
an instance of the class is created. At the time of calling constructor, memory
for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and
parameterized constructor.
Note: It is called constructor because it constructs the values at the time of
object creation. It is not necessary to write a constructor for a class. It is because
java compiler creates a default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so
primarily there are three types of constructors in Java are mentioned
below:
• 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.
// Java Program to demonstrate
// Default Constructor
import [Link].*;
// Driver class
class GFG {
// Default Constructor
GFG() { [Link]("Default constructor"); }
// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}
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.
Example:
Java
// Java Program for Parameterized Constructor
import [Link].*;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id)
{
[Link] = name;
[Link] = id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("Avinash", 68);
[Link]("GeekName :" + [Link]
+ " and GeekId :" + [Link]);
}
}
Output
GeekName :Avinash and GeekId :68
Remember: Does constructor return any value?
There are no “return value” statements in the constructor, but the
constructor returns the current class instance. We can write ‘return’
inside a constructor.
3. Copy Constructor in Java
Unlike other constructors copy constructor is passed with another object
which copies the data available from the passed object to the newly
created object.
Note: In Java,there is no such inbuilt copy constructor available like in
other programming languages such as C++, instead we can create our
own copy constructor by passing the object of the same class to the
other instance(object) of the class.
Example:
Java
// Java Program for Copy Constructor
import [Link].*;
class Geek {
// data members of the class.
String name;
int id;
// Parameterized Constructor
Geek(String name, int id)
{
[Link] = name;
[Link] = id;
}
// Copy Constructor
Geek(Geek obj2)
{
[Link] = [Link];
[Link] = [Link];
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
[Link]("First Object");
Geek geek1 = new Geek("Avinash", 68);
[Link]("GeekName :" + [Link]
+ " and GeekId :" + [Link]);
[Link]();
// This would invoke the copy constructor.
Geek geek2 = new Geek(geek1);
[Link](
"Copy Constructor used Second Object");
[Link]("GeekName :" + [Link]
+ " and GeekId :" + [Link]);
}
}
Output
First Object
GeekName :Avinash and GeekId :68
Copy Constructor used Second Object
GeekName :Avinash and GeekId :68
Coupling
Coupling refers to the knowledge or information or dependency of another
class. It arises when classes are aware of each other. If a class has the details
information of another class, there is strong coupling. In Java, we use private,
protected, and public modifiers to display the visibility level of a class, method,
and field. You can use interfaces for the weaker coupling because there is no
concrete implementation.
Cohesion
Cohesion refers to the level of a component which performs a single well-
defined task. A single well-defined task is done by a highly cohesive method.
The weakly cohesive method will split the task into separate parts. The [Link]
package is a highly cohesive package because it has I/O related classes and
interface. However, the [Link] package is a weakly cohesive package because
it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object
can be associated with one object or many objects. There can be four types of
association between the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
Let's understand the relationship with real-time examples. For example, One
country can have one prime minister (one to one), and a prime minister can
have many ministers (one to many). Also, many MP's can have one prime
minister (many to one), and many ministers can have many departments
(many to many).
Association can be undirectional or bidirectional.
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the
relationship where one object contains other objects as a part of its state. It
represents the weak relationship between objects. It is also termed as a has-
a relationship in Java. Like, inheritance represents the is-a relationship. It is
another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition
represents the relationship where one object contains other objects as a part
of its state. There is a strong relationship between the containing object and
the dependent object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the child objects will
be deleted automatically.
Java Package
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import [Link]
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class
A java package is a group of similar types of classes, interfaces and sub-
packages.
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
1. //save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
2. javac -d . [Link]
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you
can use . (dot).
How to run java package program
You need to use fully qualified name e.g. [Link] etc to run the class.
To Compile: javac -d . [Link]
To Run: java [Link]
Output:Welcome to package
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
Example of package that import the packagename.*
1. //save by [Link]
2. package pack;
3. public class A{
4. public void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. [Link]();
9. }
10. }
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will
be accessible.
Example of package by import [Link]
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. [Link]();
9. }
10. }
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and
[Link] packages contain Date class.
Example of package by import fully qualified name
1. //save by [Link]
2. package pack;
3. public class A{
4. public void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. [Link]();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you
need to import the subpackage as well.
Note: Sequence of the program must be package then
import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
1. ackage [Link];
2. class Simple{
3. public static void main(String args[]){
4. [Link]("Hello subpackage");
5. }
6. }
To Compile: javac -d . [Link]
To Run: java [Link]
Output:Hello subpackage
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of [Link] source file in classes
folder of c: drive. For example:
1. //save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes [Link]
To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java [Link]
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
Multithreading in Java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process
allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving
and loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
Note: At least one process is required for each thread.
What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a
separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads. It uses a shared memory area.
Java Thread class
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
Java Thread Methods
S.N. Modifier and Type Method
1)
void start()
2) void run()
3) static void sleep()
4) static Thread currentThread()
5) void join()
6) int getPriority()
7) void setPriority()
8) String getName()
9) void setName()
10) long getId()
11) boolean isAlive()
12) static void yield()
13) void suspend()
14) void resume()
15) void stop()
16) void destroy()
17) boolean isDaemon()
18) void setDaemon()
19) void interrupt()
20) boolean isinterrupted()
21) static boolean interrupted()
22) static int activeCount()
23) void checkAccess()
24) static boolean holdLock()
25) static void dumpStack()
26) StackTraceElement[] getStackTrace()
27) static int enumerate()
28) [Link] getState()
29) ThreadGroup getThreadGroup()
30) String toString()
31) void notify()
32) void notifyAll()
33) void setContextClassLoader()
34) ClassLoader getContextClassLoader()
static
35) getDefaultUncaughtExceptionHandler()
[Link]
36) static void setDefaultUncaughtExceptionHandler()
Do You Know
o How to perform two tasks by two threads?
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states
are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
Explanation of Different Thread States
New: Whenever a new thread is created, it is always in the new state. For a
thread in the new state, the code has not been run yet and thus has not begun
its execution.
Active: When a thread invokes the start() method, it moves from the new state
to the active state. The active state contains two states within it: one
is runnable, and the other is running.
Multithreading in Java
Last Updated : 24 Feb, 2021
••
•
Multithreading is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of CPU. Each part of such
program is called a thread. So, threads are light-weight processes within a
process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the [Link] class. This class overrides
the run() method available in the Thread class. A thread begins its life inside
run() method. We create an object of our new class and call start() method to
start the execution of a thread. Start() invokes the run() method on the Thread
object.
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
[Link](
"Thread " + [Link]().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
[Link]("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
[Link]();
}
}
}
COMPLETED……
UNIT-2 -------------------------------
JAVA APPLETS—
An applet is a program written in the Java programming language that can be included in an HTML
page, much in the same way an image is included in a page. When you use a Java technology-enabled
browser to view a page that contains an applet, the applet's code is transferred to your system and
executed by the browser's Java Virtual Machine (JVM)
Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.
Hierarchy of Applet
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
[Link] class
For creating any applet [Link] class must be inherited. It provides
4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only
once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only
once
[Link] class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
3. //[Link]
4. import [Link];
5. import [Link];
6. public class First extends Applet{
7.
8. public void paint(Graphics g){
9. [Link]("welcome",150,150);
10. }
11.
12. }
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Displaying Graphics in Applet
[Link] class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to
draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is
used to fill rectangle with the default color and specified width and
height.
4. public abstract void drawOval(int x, int y, int width, int height): is
used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is
used to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics
current color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics
current font to the specified font.
Example of Graphics in applet:
1. import [Link];
2. import [Link].*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. [Link]([Link]);
8. [Link]("Welcome",50, 50);
9. [Link](20,30,20,300);
10. [Link](70,100,30,30);
11. [Link](170,100,30,30);
12. [Link](70,200,30,30);
13.
14. [Link]([Link]);
15. [Link](170,200,30,30);
16. [Link](90,150,30,30,30,270);
17. [Link](270,150,30,30,0,180);
18.
19. }
20. }
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is
required to be displayed. The [Link] class provide a method
drawImage() to display the image.
Syntax of drawImage() method:
1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
How to get the object of Image:
The [Link] class provides getImage() method that returns the object of
Image. Syntax:
1. public Image getImage(URL u, String image){}
Other required methods of Applet class to display image:
1. public URL getDocumentBase(): is used to return the URL of the document in
which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
Example of displaying image in applet:
1. import [Link].*;
2. import [Link].*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"[Link]");
11. }
12.
13. public void paint(Graphics g) {
14. [Link](picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object
would also be treated as ImageObserver because Applet class indirectly extends the
Component class.
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be moved.
Example of animation in applet:
1. import [Link].*;
2. import [Link].*;
3. public class AnimationExample extends Applet {
4.
5. Image picture;
6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
9. }
10.
11. public void paint(Graphics g) {
12. for(int i=0;i<500;i++){
13. [Link](picture, i,30, this);
14.
15. try{[Link](100);}catch(Exception e){}
16. }
17. }
18. }
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object
would also be treated as ImageObserver because Applet class indirectly extends the
Component class.
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's
see the simple example of event handling in applet that prints a message by click on
the button.
Example of EventHandling in applet:
1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class EventApplet extends Applet implements ActionListene
r{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. [Link](30,40,150,20);
11.
12. b=new Button("Click");
13. [Link](80,150,60,50);
14.
15. add(b);add(tf);
16. [Link](this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. [Link]("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is
invoked only once.
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
7. Java AWT Tutorial
8. Java AWT (Abstract Window Toolkit) is an API to develop Graphical User
Interface (GUI) or windows-based applications in Java.
9. Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system. AWT is heavy
weight i.e. its components are using the resources of underlying
operating system (OS).
10. The [Link] package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
11. The AWT tutorial will help the user to understand Java GUI programming
in simple and easy steps.
12. Why AWT is platform independent?
13. Java AWT calls the native platform calls the native platform (operating
systems) subroutine for creating API components like TextField,
ChechBox, button, etc.
14. For example, an AWT GUI with components like TextField, label and
button will have different look and feel for the different platforms like
Windows, MAC OS, and Unix. The reason for this is the platforms have
different view for their native components and AWT directly calls the
native subroutine that creates those components.
15. In simple words, an AWT application will look like a windows application
in Windows OS whereas it will look like a Mac application in the MAC OS.
[Link] AWT Hierarchy
17. The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can
add a container inside container.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window. We need to create
an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It
is generic container for holding the components. It can have other components
like button, text field etc. An instance of Panel class creates a container, in which
we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame
is most widely used container while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
Sets the size (width and height) of the
public void setSize(int width,int height)
component.
public void setLayout(LayoutManager Defines the layout manager for the
m) component.
Changes the visibility of the component,
public void setVisible(boolean status)
by default false.
Java AWT Example
Java AWT Button
A button is basically a control component with a label that generates an event
when pushed. The Button class is used to create a labeled button that has
platform independent implementation. The application result in some action
when the button is pushed.
When we press a button and release it, AWT sends an instance
of ActionEvent to that button by calling processEvent on the button.
The processEvent method of the button receives the all the events, then it
passes an action event by calling its own method processActionEvent. This
method passes the action event on to action listeners that are interested in the
action events generated by the button.
To perform an action on a button being pressed and released,
the ActionListener interface needs to be implemented. The registered new
listener can receive events from the button by
calling addActionListener method of the button. The Java application can use
the button's action command as a messaging protocol.
AWT Button Class Declaration
1. public class Button extends Component implements Accessible
Button Class Constructors
Following table shows the types of Button class constructors
Sr. no. Constructor Description
It constructs a new button
1. Button( ) with an empty string i.e. it
has no label.
It constructs a new button
2. Button (String text) with given string as its
label.
Button Class Methods
Sr. no. Method Description
It sets the string
1. void setText (String text)
message on the button
It fetches the String
2. String getText()
message on the button.
It sets the label of
3. void setLabel (String label) button with the
specified string.
It fetches the label of
4. String getLabel()
the button.
It creates the peer of
5. void addNotify()
the button.
It fetched the
AccessibleContext accessible context
6.
getAccessibleContext() associated with the
button.
It adds the specified
void
action listener to get
7. addActionListener(ActionListener
the action events from
l)
the button.
It returns the command
name of the action
8. String getActionCommand()
event fired by the
button.
It returns an array of all
ActionListener[ ] the action listeners
9.
getActionListeners() registered on the
button.
It returns an array of all
the objects currently
T[ ]
10. registered as
getListeners(ClasslistenerType)
FooListeners upon this
Button.
It returns the string
11. protected String paramString() which represents the
state of button.
It process the action
protected void events on the button by
12. processActionEvent (ActionEvent dispatching them to a
e) registered
ActionListener object.
protected void processEvent It process the events on
13.
(AWTEvent e) the button
It removes the specified
action listener so that it
void removeActionListener
14. no longer receives
(ActionListener l)
action events from the
button.
It sets the command
void setActionCommand(String name for the action
15.
command) event given by the
button.
Note: The Button class inherits methods from [Link] and
[Link] classes.
Java AWT Button Example
Example 1:
[Link]
1. import [Link].*;
2. public class ButtonExample {
3. public static void main (String[] args) {
4.
5. // create instance of frame with the label
6. Frame f = new Frame("Button Example");
7.
8. // create instance of button with label
9. Button b = new Button("Click Here");
10.
11. // set the position for the button in frame
12. [Link](50,100,80,30);
13.
14. // add button to the frame
15. [Link](b);
16. // set size, layout and visibility of frame
17. [Link](400,400);
18. [Link](null);
19. [Link](true);
20. }
21. }
22. / importing necessary libraries
23. import [Link].*;
24. import [Link].*;
25. import [Link].*;
26.
27. public class ButtonExample2
28. {
29. // creating instances of Frame class and Button class
30. Frame fObj;
31. Button button1, button2, button3;
32. // instantiating using the constructor
33. ButtonExample2() {
34. fObj = new Frame ("Frame to display buttons");
35. button1 = new Button();
36. button2 = new Button ("Click here");
37. button3 = new Button();
38. [Link]("Button 3");
39. [Link](button1);
40. [Link](button2);
41. [Link](button3);
42. [Link](new FlowLayout());
43. [Link](300,400);
44. [Link](true);
45. }
46.// main method
47. public static void main (String args[])
48. {
[Link] ButtonExample2();
50. }
51. }
Java AWT Label
The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed.
To create a label, we need to create the object of Label class.
AWT Label Class Declaration
1. public class Label extends Component implements Accessible
AWT Label Fields
The [Link] class has following fields:
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
Label class Constructors
Sr. no. Constructor Description
It constructs an empty
1. Label()
label.
It constructs a label with
2. Label(String text) the given string (left
justified by default).
It constructs a label with
Label(String text, int
3. the specified string and
alignement)
the specified alignment.
Label Class Methods
Specified
Sr. no. Method name Description
It sets the texts for label
1. void setText(String text)
with the specified text.
It sets the alignment for
void setAlignment(int
2. label with the specified
alignment)
alignment.
3. String getText() It gets the text of the label
It gets the current
4. int getAlignment()
alignment of the label.
It creates the peer for the
5. void addNotify()
label.
It gets the Accessible
AccessibleContext
6. Context associated with
getAccessibleContext()
the label.
protected String It returns the string the
7.
paramString() state of the label.
Method inherited
The above methods are inherited by the following classes:
o [Link]
o [Link]
Java AWT Label Example
In the following example, we are creating two labels l1 and l2 using the
Label(String text) constructor and adding them into the frame.
[Link]
1. import [Link].*;
2.
3. public class LabelExample {
4. public static void main(String args[]){
5.
6. // creating the object of Frame class and Label class
7. Frame f = new Frame ("Label example");
8. Label l1, l2;
9.
10. // initializing the labels
11. l1 = new Label ("First Label.");
12. l2 = new Label ("Second Label.");
13.
14. // set the location of label
15. [Link](50, 100, 100, 30);
16. [Link](50, 150, 100, 30);
17.
18. // adding labels to the frame
19. [Link](l1);
20. [Link](l2);
21.
22. // setting size, layout and visibility of frame
23. [Link](400,400);
24. [Link](null);
25. [Link](true);
26. }
27. }
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key
typed), the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the
ActionEvent is enabled on the text field, then the ActionEvent may be fired by
pressing return key. The event is handled by the ActionListener interface.
AWT TextField Class Declaration
1. public class TextField extends TextComponent
TextField Class constructors
Sr. no. Constructor Description
It constructs a new text
1. TextField()
field component.
It constructs a new text
field initialized with the
2. TextField(String text)
given string text to be
displayed.
It constructs a new
3. TextField(int columns) textfield (empty) with
given number of columns.
It constructs a new text
TextField(String text, int field with the given text
4.
columns) and given number of
columns (width).
TextField Class Methods
Sr. no. Method name Description
It creates the peer of
1. void addNotify()
text field.
It tells whether text
2. boolean echoCharIsSet() field has character set
for echoing or not.
It adds the specified
void action listener to
3.
addActionListener(ActionListener l) receive action events
from the text field.
4. ActionListener[] getActionListeners() It returns array of all
action listeners
registered on text
field.
It fetches the
AccessibleContext accessible context
5.
getAccessibleContext() related to the text
field.
It fetches the number
6. int getColumns() of columns in text
field.
It fetches the
7. char getEchoChar() character that is used
for echoing.
It fetches the
8. Dimension getMinimumSize() minimum dimensions
for the text field.
It fetches the
minimum dimensions
Dimension getMinimumSize(int
9. for the text field with
columns)
specified number of
columns.
It fetches the
10. Dimension getPreferredSize() preferred size of the
text field.
It fetches the
preferred size of the
Dimension getPreferredSize(int
11. text field with
columns)
specified number of
columns.
It returns a string
12. protected String paramString() representing state of
the text field.
It processes action
events occurring in
protected void the text field by
13.
processActionEvent(ActionEvent e) dispatching them to a
registered
ActionListener object.
protected void It processes the event
14.
processEvent(AWTEvent e) on text field.
It removes specified
void action listener so that
15. removeActionListener(ActionListener it doesn't receive
l) action events
anymore.
It sets the number of
16. void setColumns(int columns)
columns in text field.
It sets the echo
17. void setEchoChar(char c)
character for text field.
It sets the text
presented by this text
18. void setText(String t)
component to the
specified text.
Method Inherited
The AWT TextField class inherits the methods from below classes:
1. [Link]
2. [Link]
3. [Link]
Java AWT TextField Example
[Link]
1. // importing AWT class
2. import [Link].*;
3. public class TextFieldExample1 {
4. // main method
5. public static void main(String args[]) {
6. // creating a frame
7. Frame f = new Frame("TextField Example");
8.
9. // creating objects of textfield
10. TextField t1, t2;
11. // instantiating the textfield objects
12. // setting the location of those objects in the frame
13. t1 = new TextField("Welcome to Javatpoint.");
14. [Link](50, 100, 200, 30);
15. t2 = new TextField("AWT Tutorial");
16. [Link](50, 150, 200, 30);
17. // adding the components to frame
18. [Link](t1);
19. [Link](t2);
20. // setting size, layout and visibility of frame
21. [Link](400,400);
22. [Link](null);
23. [Link](true);
24. }
25. }
Java AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the
text area becomes larger than the viewable area, the scroll bar appears
automatically which helps us to scroll the text up and down, or right and left.
AWT TextArea Class Declaration
1. public class TextArea extends TextComponent
Fields of TextArea Class
The fields of [Link] class are as follows:
o static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical
scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the
horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the
vertical scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text
area.
Class constructors:
Sr. no. Constructor Description
It constructs a new and empty
1. TextArea()
text area with no text in it.
It constructs a new text area with
specified number of rows and
2. TextArea (int row, int column)
columns and empty string as
text.
It constructs a new text area and
3. TextArea (String text)
displays the specified text in it.
It constructs a new text area with
TextArea (String text, int row, the specified text in the text area
4.
int column) and specified number of rows
and columns.
It construcst a new text area with
TextArea (String text, int row, specified text in text area and
5.
int column, int scrollbars) specified number of rows and
columns and visibility.
Methods Inherited
The methods of TextArea class are inherited from following classes:
o [Link]
o [Link]
o [Link]
TetArea Class Methods
Sr. no. Method name Description
It creates a peer of text
1. void addNotify()
area.
It appends the specified
2. void append(String str) text to the current text of
text area.
It returns the accessible
AccessibleContext
3. context related to the text
getAccessibleContext()
area
It returns the number of
4. int getColumns()
columns of text area.
It determines the
Dimension
5. minimum size of a text
getMinimumSize()
area.
It determines the
Dimension minimum size of a text
6. getMinimumSize(int rows, area with the given
int columns) number of rows and
columns.
It determines the
Dimension
7. preferred size of a text
getPreferredSize()
area.
It determines the
Dimension
preferred size of a text
8. preferredSize(int rows, int
area with given number of
columns)
rows and columns.
It returns the number of
9. int getRows()
rows of text area.
It returns an enumerated
value that indicates which
10. int getScrollbarVisibility()
scroll bars the text area
uses.
It inserts the specified text
void insert(String str, int
11. at the specified position in
pos)
this text area.
It returns a string
protected String
12. representing the state of
paramString()
this TextArea.
It replaces text between
the indicated start and
void replaceRange(String
13. end positions with the
str, int start, int end)
specified replacement
text.
void setColumns(int It sets the number of
14.
columns) columns for this text area.
It sets the number of rows
15. void setRows(int rows)
for this text area.
Java AWT TextArea Example
The below example illustrates the simple implementation of TextArea where
we are creating a text area using the constructor TextArea(String text) and
adding it to the frame.
TextAreaExample .java
1. //importing AWT class
2. import [Link].*;
3. public class TextAreaExample
4. {
5. // constructor to initialize
6. TextAreaExample() {
7. // creating a frame
8. Frame f = new Frame();
9. // creating a text area
10. TextArea area = new TextArea("Welcome to javatpoint");
11. // setting location of text area in frame
12. [Link](10, 30, 300, 300);
13. // adding text area to frame
14. [Link](area);
15. // setting size, layout and visibility of frame
16. [Link](400, 400);
17. [Link](null);
18. [Link](true);
19. }
20. // main method
21. public static void main(String args[])
22. {
23. new TextAreaExample();
24. }
25. }
Java AWT TextArea Example with ActionListener
The following example displays a text area in the frame where it extends the
Frame class and implements ActionListener interface. Using ActionListener the
event is generated on the button press, where we are counting the number of
character and words entered in the text area.
[Link]
1. // importing necessary libraries
2. import [Link].*;
3. import [Link].*;
4. // our class extends the Frame class to inherit its properties
5. // and implements ActionListener interface to override its methods
6. public class TextAreaExample2 extends Frame implements ActionL
istener {
7. // creating objects of Label, TextArea and Button class.
8. Label l1, l2;
9. TextArea area;
10. Button b;
11. // constructor to instantiate
12. TextAreaExample2() {
13. // instantiating and setting the location of components on the frame
14. l1 = new Label();
15. [Link](50, 50, 100, 30);
16. l2 = new Label();
17. [Link](160, 50, 100, 30);
18. area = new TextArea();
19. [Link](20, 100, 300, 300);
20. b = new Button("Count Words");
21. [Link](100, 400, 100, 30);
22.
23. // adding ActionListener to button
24. [Link](this);
25.
26. // adding components to frame
27. add(l1);
28. add(l2);
29. add(area);
30. add(b);
31. // setting the size, layout and visibility of frame
32. setSize(400, 450);
33. setLayout(null);
34. setVisible(true);
35. }
36. // generating event text area to count number of words and characte
rs
37. public void actionPerformed(ActionEvent e) {
38. String text = [Link]();
39. String words[]=[Link]("\\s");
40. [Link]("Words: "+[Link]);
41. [Link]("Characters: "+[Link]());
42. }
43. // main method
44. public static void main(String[] args) {
45. new TextAreaExample2();
46.}
47. }
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or
from "off" to "on".
AWT Checkbox Class Declaration
1. public class Checkbox extends Component implements ItemSelect
able, Accessible
Checkbox Class Constructors
Sr. no. Constructor Description
It constructs a checkbox
1. Checkbox()
with no string as the label.
It constructs a checkbox
2. Checkbox(String label)
with the given label.
It constructs a checkbox
Checkbox(String label,
3. with the given label and
boolean state)
sets the given state.
It constructs a checkbox
Checkbox(String label,
with the given label, set
4. boolean state,
the given state in the
CheckboxGroup group)
specified checkbox group.
It constructs a checkbox
Checkbox(String label, with the given label, in the
5. CheckboxGroup group, given checkbox group
boolean state) and set to the specified
state.
Method inherited by Checkbox
The methods of Checkbox class are inherited by following classes:
o [Link]
o [Link]
Checkbox Class Methods
Sr. no. Method name Description
void addItemListener(ItemListener
1. It adds the given item
IL)
listener to get the item
events from the
checkbox.
It fetches the
AccessibleContext
2. accessible context of
getAccessibleContext()
checkbox.
It creates the peer of
3. void addNotify()
checkbox.
CheckboxGroup It determines the
4.
getCheckboxGroup() group of checkbox.
It returns an array of
the item listeners
5. ItemListener[] getItemListeners()
registered on
checkbox.
It fetched the label of
6. String getLabel()
checkbox.
It returns an array of all
7. T[] getListeners(ClasslistenerType) the objects registered
as FooListeners.
It returns an array (size
1) containing checkbox
8. Object[] getSelectedObjects() label and returns null if
checkbox is not
selected.
It returns true if the
9. boolean getState() checkbox is on, else
returns off.
It returns a string
10. protected String paramString() representing the state
of checkbox.
protected void It processes the event
11.
processEvent(AWTEvent e) on checkbox.
It process the item
events occurring in
protected void the checkbox by
12.
processItemEvent(ItemEvent e) dispatching them to
registered
ItemListener object.
It removes the
specified item listener
void so that the item
13.
removeItemListener(ItemListener l) listener doesn't receive
item events from the
checkbox anymore.
void It sets the checkbox's
14. setCheckboxGroup(CheckboxGroup group to the given
g) checkbox.
It sets the checkbox's
15. void setLabel(String label) label to the string
argument.
It sets the state of
16. void setState(boolean state) checkbox to the
specified state.
Java AWT Checkbox Example
In the following example we are creating two checkboxes using the
Checkbox(String label) constructo and adding them into the Frame using add()
method.
[Link]
1. // importing AWT class
2. import [Link].*;
3. public class CheckboxExample1
4. {
5. // constructor to initialize
6. CheckboxExample1() {
7. // creating the frame with the title
8. Frame f = new Frame("Checkbox Example");
9. // creating the checkboxes
10. Checkbox checkbox1 = new Checkbox("C++");
11. [Link](100, 100, 50, 50);
12. Checkbox checkbox2 = new Checkbox("Java", true);
13. // setting location of checkbox in frame
14. [Link](100, 150, 50, 50);
15. // adding checkboxes to frame
16. [Link](checkbox1);
17. [Link](checkbox2);
18.
19. // setting size, layout and visibility of frame
20. [Link](400,400);
21. [Link](null);
22. [Link](true);
23. }
24. // main method
25. public static void main (String args[])
26. {
27. new CheckboxExample1();
28. }
29. }
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox.
At a time only one check box button is allowed to be in "on" state and remaining
check box button in "off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no
special control for creating radio buttons in AWT.
AWT CheckboxGroup Class Declaration
1. public class CheckboxGroup extends Object implements Serializabl
e
Java AWT CheckboxGroup Example
1. import [Link].*;
2. public class CheckboxGroupExample
3. {
4. CheckboxGroupExample(){
5. Frame f= new Frame("CheckboxGroup Example");
6. CheckboxGroup cbg = new CheckboxGroup();
7. Checkbox checkBox1 = new Checkbox("C++", cbg, false);
8. [Link](100,100, 50,50);
9. Checkbox checkBox2 = new Checkbox("Java", cbg, true);
10. [Link](100,150, 50,50);
11. [Link](checkBox1);
12. [Link](checkBox2);
13. [Link](400,400);
14. [Link](null);
15. [Link](true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. }
21. }
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
1. public class Choice extends Component implements ItemSelectable, Accessible
Choice Class constructor
Sr. no. Constructor Description
1. Choice() It constructs a new choice menu.
Methods inherited by class
The methods of Choice class are inherited by following classes:
o [Link]
o [Link]
Choice Class Methods
Sr. no. Method name Description
It adds an item to the choice
1. void add(String item)
menu.
It adds the item listener that
2. void addItemListener(ItemListener l) receives item events from the
choice menu.
3. void addNotify() It creates the peer of choice.
AccessibleContext It gets the accessbile context
4.
getAccessibleContext() related to the choice.
It gets the item (string) at the
5. String getItem(int index) given index position in the
choice menu.
It returns the number of items
6. int getItemCount()
of the choice menu.
It returns an array of all item
7. ItemListener[] getItemListeners()
listeners registered on choice.
Returns an array of all the
8. T[] getListeners(ClasslistenerType) objects currently registered as
FooListeners upon this Choice.
Returns the index of the
9. int getSelectedIndex()
currently selected item.
Gets a representation of the
10. String getSelectedItem()
current choice as a string.
Returns an array (length 1)
11. Object[] getSelectedObjects() containing the currently
selected item.
Inserts the item into this choice
12. void insert(String item, int index)
at the specified position.
Returns a string representing
13. protected String paramString()
the state of this Choice menu.
protected void It processes the event on the
14.
processEvent(AWTEvent e) choice.
Processes item events
occurring on this Choice menu
protected void processItemEvent
15. by dispatching them to any
(ItemEvent e)
registered ItemListener
objects.
It removes an item from the
16. void remove(int position) choice menu at the given index
position.
It removes the first occurrence
17. void remove(String item)
of the item from choice menu.
It removes all the items from
18. void removeAll()
the choice menu.
It removes the mentioned item
void removeItemListener listener. Thus is doesn't receive
19.
(ItemListener l) item events from the choice
menu anymore.
It changes / sets the selected
20. void select(int pos) item in the choice menu to the
item at given index position.
It changes / sets the selected
item in the choice menu to the
21. void select(String str) item whose string value is
equal to string specified in the
argument.
Java AWT Choice Example
In the following example, we are creating a choice menu using Choice() constructor. Then we add
5 items to the menu using add() method and Then add the choice menu into the Frame.
[Link]
1. // importing awt class
2. import [Link].*;
3. public class ChoiceExample1 {
4.
5. // class constructor
6. ChoiceExample1() {
7.
8. // creating a frame
9. Frame f = new Frame();
10.
11. // creating a choice component
12. Choice c = new Choice();
13.
14. // setting the bounds of choice menu
15. [Link](100, 100, 75, 75);
16.
17. // adding items to the choice menu
18. [Link]("Item 1");
19. [Link]("Item 2");
20. [Link]("Item 3");
21. [Link]("Item 4");
22. [Link]("Item 5");
23.
24. // adding choice menu to frame
25. [Link](c);
26.
27. // setting size, layout and visibility of frame
28. [Link](400, 400);
29. [Link](null);
30. [Link](true);
31. }
32.
33. // main method
34. public static void main(String args[])
35. {
36. new ChoiceExample1();
37. }
38. }
Java AWT List
The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the
Component class.
AWT List class Declaration
1. public class List extends Component implements ItemSelectable, A
ccessible
AWT List Class Constructors
Sr. no. Constructor Description
It constructs a new scrolling
1. List()
list.
It constructs a new scrolling
2. List(int row_num) list initialized with the given
number of rows visible.
It constructs a new scrolling
List(int row_num, Boolean
3. list initialized which displays
multipleMode)
the given number of rows.
Methods Inherited by the List Class
The List class methods are inherited by following classes:
o [Link]
o [Link]
List Class Methods
Sr. no. Method name Description
It adds the specified
1. void add(String item) item into the end of
scrolling list.
It adds the specified
2. void add(String item, int index) item into list at the
given index position.
It adds the specified
void action listener to
3.
addActionListener(ActionListener l) receive action events
from list.
It adds specified item
4. void addItemListener(ItemListener l) listener to receive item
events from list.
5. void addNotify() It creates peer of list.
It deselects the item at
6. void deselect(int index)
given index position.
It fetches the
AccessibleContext
7. accessible context
getAccessibleContext()
related to the list.
It returns an array of
8. ActionListener[] getActionListeners() action listeners
registered on the list.
It fetches the item
9. String getItem(int index) related to given index
position.
It gets the
10. int getItemCount() count/number of
items in the list.
It returns an array of
11. ItemListener[] getItemListeners() item listeners
registered on the list.
It fetched the items
12. String[] getItems()
from the list.
It gets the minimum
13. Dimension getMinimumSize()
size of a scrolling list.
It gets the minimum
Dimension getMinimumSize(int
14. size of a list with given
rows)
number of rows.
It gets the preferred
15. Dimension getPreferredSize()
size of list.
It gets the preferred
Dimension getPreferredSize(int
16. size of list with given
rows)
number of rows.
It fetches the count of
17. int getRows()
visible rows in the list.
It fetches the index of
18. int getSelectedIndex()
selected item of list.
It gets the selected
19. int[] getSelectedIndexes()
indices of the list.
It gets the selected
20. String getSelectedItem()
item on the list.
It gets the selected
21. String[] getSelectedItems()
items on the list.
It gets the selected
22. Object[] getSelectedObjects() items on scrolling list
in array of objects.
It gets the index of an
item which was made
23. int getVisibleIndex()
visible by method
makeVisible()
It makes the item at
24. void makeVisible(int index)
given index visible.
It returns true if given
25. boolean isIndexSelected(int index) item in the list is
selected.
It returns the true if list
26. boolean isMultipleMode() allows multiple
selections.
It returns parameter
string representing
27. protected String paramString()
state of the scrolling
list.
It process the action
events occurring on
protected void
28. list by dispatching
processActionEvent(ActionEvent e)
them to a registered
ActionListener object.
protected void It process the events
29.
processEvent(AWTEvent e) on scrolling list.
It process the item
events occurring on
protected void
30. list by dispatching
processItemEvent(ItemEvent e)
them to a registered
ItemListener object.
It removes specified
void action listener. Thus it
31. removeActionListener(ActionListener doesn't receive further
l) action events from the
list.
It removes specified
item listener. Thus it
void
32. doesn't receive further
removeItemListener(ItemListener l)
action events from the
list.
It removes the item at
33. void remove(int position) given index position
from the list.
It removes the first
34. void remove(String item) occurrence of an item
from list.
It removes all the
35. void removeAll()
items from the list.
It replaces the item at
void replaceItem(String newVal, int the given index in list
36.
index) with the new string
specified.
It selects the item at
37. void select(int index)
given index in the list.
38. void setMultipleMode(boolean b) It sets the flag which
determines whether
the list will allow
multiple selection or
not.
It removes the peer of
39. void removeNotify()
list.
Java AWT List Example
In the following example, we are creating a List component with 5 rows and
adding it into the Frame.
[Link]
1. // importing awt class
2. import [Link].*;
3.
4. public class ListExample1
5. {
6. // class constructor
7. ListExample1() {
8. // creating the frame
9. Frame f = new Frame();
10. // creating the list of 5 rows
11. List l1 = new List(5);
12.
13. // setting the position of list component
14. [Link](100, 100, 75, 75);
15.
16. // adding list items into the list
17. [Link]("Item 1");
18. [Link]("Item 2");
19. [Link]("Item 3");
20. [Link]("Item 4");
21. [Link]("Item 5");
22.
23. // adding the list to frame
24. [Link](l1);
25.
26. // setting size, layout and visibility of frame
27. [Link](400, 400);
28. [Link](null);
29. [Link](true);
30. }
31.
32. // main method
33. public static void main(String args[])
34. {
35. new ListExample1();
36. }
37. }
Java AWT Canvas
The Canvas class controls and represents a blank rectangular area where the
application can draw or trap input events from the user. It inherits
the Component class.
AWT Canvas class Declaration
1. public class Canvas extends Component implements Accessible
Canvas Class Constructors
Sr. no. Constructor Description
It constructs a new
1. Canvas()
Canvas.
It constructs a new
Canvas(GraphicConfiguration Canvas with the given
2.
config) Graphic Configuration
object.
Class methods
Sr. no. Method name Description
It creates the canvas's
1. void addNotify()
peer.
It creates a new multi
void createBufferStrategy
2. buffering strategies on
(int numBuffers)
the particular component.
It creates a new multi
void createBufferStrategy buffering strategies on
3. (int numBuffers, the particular component
BufferCapabilities caps) with the given buffer
capabilities.
It gets the accessible
AccessibleContext
4. context related to the
getAccessibleContext()
Canvas.
It returns the buffer
BufferStrategy
5. strategy used by the
getBufferStrategy()
particular component.
It paints the canvas with
6. void paint(Graphics g)
given Graphics object.
It updates the canvas with
7. void pdate(Graphics g)
given Graphics object.
Method Inherited by Canvas Class
The Canvas has inherited above methods from the following classes:
o [Link]
o [Link]
Java AWT Canvas Example
In the following example, we are creating a Canvas in the Frame and painting
a red colored oval inside it.
[Link]
1. // importing awt class
2. import [Link].*;
3.
4. // class to construct a frame and containing main method
5. public class CanvasExample
6. {
7. // class constructor
8. public CanvasExample()
9. {
10.
11. // creating a frame
12. Frame f = new Frame("Canvas Example");
13. // adding canvas to frame
14. [Link](new MyCanvas());
15.
16. // setting layout, size and visibility of frame
17. [Link](null);
18. [Link](400, 400);
19. [Link](true);
20. }
21.
22. // main method
23. public static void main(String args[])
24. {
25. new CanvasExample();
26. }
27. }
28.
29. // class which inherits the Canvas class
30. // to create Canvas
31. class MyCanvas extends Canvas
32. {
33. // class constructor
34. public MyCanvas() {
35. setBackground ([Link]);
36. setSize(300, 200);
37. }
38.
39. // paint() method to draw inside the canvas
40. public void paint(Graphics g)
41. {
42.
43. // adding specifications
44. [Link]([Link]);
45. [Link](75, 75, 150, 75);
46. }
47. }
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
It can be added to top-level container like Frame or a component like Panel.
The Scrollbar class extends the Component class.
AWT Scrollbar Class Declaration
1. public class Scrollbar extends Component implements Adjustable,
Accessible
Scrollbar Class Fields
The fields of [Link] class are as follows:
o static int HORIZONTAL - It is a constant to indicate a horizontal scroll
bar.
o static int VERTICAL - It is a constant to indicate a vertical scroll bar.
Scrollbar Class Constructors
Sr. no. Constructor Description
Constructs a new vertical
1 Scrollbar()
scroll bar.
Constructs a new scroll
2 Scrollbar(int orientation) bar with the specified
orientation.
Constructs a new scroll
bar with the specified
Scrollbar(int orientation,
orientation, initial value,
3 int value, int visible, int
visible amount, and
minimum, int maximum)
minimum and maximum
values.
Where the parameters,
o orientation: specifiey whether the scrollbar will be horizontal or
vertical.
o Value: specify the starting position of the knob of Scrollbar on its track.
o Minimum: specify the minimum width of track on which scrollbar is
moving.
o Maximum: specify the maximum width of track on which scrollbar is
moving.
Method Inherited by Scrollbar
The methods of Scrollbar class are inherited from the following classes:
o [Link]
o [Link]
Scrollbar Class Methods
Sr. no. Method name Description
It adds the given
adjustment listener to
void addAdjustmentListener
1. receive instances of
(AdjustmentListener l)
AdjustmentEvent from
the scroll bar.
It creates the peer of
2. void addNotify()
scroll bar.
It gets the block
3. int getBlockIncrement() increment of the scroll
bar.
It gets the maximum
4. int getMaximum()
value of the scroll bar.
It gets the minimum
5. int getMinimum()
value of the scroll bar.
It returns the orientation
6. int getOrientation()
of scroll bar.
It fetches the unit
7. int getUnitIncrement() increment of the scroll
bar.
It fetches the current
8. int getValue()
value of scroll bar.
It fetches the visible
9. int getVisibleAmount()
amount of scroll bar.
It returns true if the value
is in process of changing
10. boolean getValueIsAdjusting()
where action results are
being taken by the user.
It returns a string
protected String
11. representing the state of
paramString()
Scroll bar.
It processes the
adjustment event
protected void occurring on scroll bar by
12. processAdjustmentEvent dispatching them to any
(AdjustmentEvent e) registered
AdjustmentListener
objects.
protected void It processes the events
13.
processEvent(AWTEvent e) on the scroll bar.
void It removes the given
14. removeAdjustmentListener adjustment listener. Thus
(AdjustmentListener l) it no longer receives the
instances of
AdjustmentEvent from
the scroll bar.
It sets the block
15. void setBlockIncrement(int v) increment from scroll
bar.
void setMaximum (int It sets the maximum
16.
newMaximum) value of the scroll bar.
void setMinimum (int It sets the minimum
17.
newMinimum) value of the scroll bar.
void setOrientation (int It sets the orientation for
18.
orientation) the scroll bar.
It sets the unit increment
19. void setUnitIncrement(int v)
for the scroll bar.
It sets the value of scroll
20. void setValue (int newValue) bar with the given
argument value.
It sets the
void setValueIsAdjusting
21. valueIsAdjusting
(boolean b)
property to scroll bar.
It sets the values of four
void setValues (int value, int properties for scroll bar:
22. visible, int minimum, int value, visible amount,
maximum) minimum and
maximum.
void setVisibleAmount (int It sets the visible amount
23.
newAmount) of the scroll bar.
It gets the accessible
AccessibleContext
24. context related to the
getAccessibleContext()
scroll bar.
It returns an array of al
AdjustmentListener[] lthe adjustment listeners
25.
getAdjustmentListeners() registered on the scroll
bar.
It returns an array if all
objects that are
T[]
26. registered as
getListeners(ClasslistenerType)
FooListeners on the scroll
bar currently.
Java AWT Scrollbar Example
In the following example, we are creating a scrollbar using the Scrollbar() and
adding it into the Frame.
[Link]
1. // importing awt package
2. import [Link].*;
3.
4. public class ScrollbarExample1 {
5.
6. // class constructor
7. ScrollbarExample1() {
8.
9. // creating a frame
10. Frame f = new Frame("Scrollbar Example");
11. // creating a scroll bar
12. Scrollbar s = new Scrollbar();
13.
14. // setting the position of scroll bar
15. [Link] (100, 100, 50, 100);
16.
17. // adding scroll bar to the frame
18. [Link](s);
19.
20. // setting size, layout and visibility of frame
21. [Link](400, 400);
22. [Link](null);
23. [Link](true);
24. }
25.
26. // main method
27. public static void main(String args[]) {
28. new ScrollbarExample1();
29. }
30. }
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed
on the menu bar. It inherits the MenuItem class.
AWT MenuItem class declaration
1. public class MenuItem extends MenuComponent implements Acc
essible
AWT Menu class declaration
1. public class Menu extends MenuItem implements MenuContainer,
Accessible
Java AWT MenuItem and Menu Example
1. import [Link].*;
2. class MenuExample
3. {
4. MenuExample(){
5. Frame f= new Frame("Menu and MenuItem Example");
6. MenuBar mb=new MenuBar();
7. Menu menu=new Menu("Menu");
8. Menu submenu=new Menu("Sub Menu");
9. MenuItem i1=new MenuItem("Item 1");
10. MenuItem i2=new MenuItem("Item 2");
11. MenuItem i3=new MenuItem("Item 3");
12. MenuItem i4=new MenuItem("Item 4");
13. MenuItem i5=new MenuItem("Item 5");
14. [Link](i1);
15. [Link](i2);
16. [Link](i3);
17. [Link](i4);
18. [Link](i5);
19. [Link](submenu);
20. [Link](menu);
21. [Link](mb);
22. [Link](400,400);
23. [Link](null);
24. [Link](true);
25. }
26. public static void main(String args[])
27. {
28. new MenuExample();
29. }
30. }
Java AWT PopupMenu
PopupMenu can be dynamically popped up at specific position within a
component. It inherits the Menu class.
AWT PopupMenu class declaration
1. public class PopupMenu extends Menu implements MenuContaine
r, Accessible
Java AWT PopupMenu Example
1. import [Link].*;
2. import [Link].*;
3. class PopupMenuExample
4. {
5. PopupMenuExample(){
6. final Frame f= new Frame("PopupMenu Example");
7. final PopupMenu popupmenu = new PopupMenu("Edit");
8. MenuItem cut = new MenuItem("Cut");
9. [Link]("Cut");
10. MenuItem copy = new MenuItem("Copy");
11. [Link]("Copy");
12. MenuItem paste = new MenuItem("Paste");
13. [Link]("Paste");
14. [Link](cut);
15. [Link](copy);
16. [Link](paste);
17. [Link](new MouseAdapter() {
18. public void mouseClicked(MouseEvent e) {
19. [Link](f , [Link](), [Link]());
20. }
21. });
22. [Link](popupmenu);
23. [Link](400,400);
24. [Link](null);
25. [Link](true);
26. }
27. public static void main(String args[])
28. {
29. new PopupMenuExample();
30. }
31. }
Java AWT Panel
The Panel is a simplest container class. It provides space in which an application
can attach any other component. It inherits the Container class.
It doesn't have title bar.
AWT Panel class declaration
1. public class Panel extends Container implements Accessible
Java AWT Panel Example
1. import [Link].*;
2. public class PanelExample {
3. PanelExample()
4. {
5. Frame f= new Frame("Panel Example");
6. Panel panel=new Panel();
7. [Link](40,80,200,200);
8. [Link]([Link]);
9. Button b1=new Button("Button 1");
10. [Link](50,100,80,30);
11. [Link]([Link]);
12. Button b2=new Button("Button 2");
13. [Link](100,100,80,30);
14. [Link]([Link]);
15. [Link](b1); [Link](b2);
16. [Link](panel);
17. [Link](400,400);
18. [Link](null);
19. [Link](true);
20. }
21. public static void main(String args[])
22. {
23. new PanelExample();
24. }
25. }
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used
to take some form of input from the user. It inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and
minimize buttons but Dialog doesn't have.
AWT Dialog class declaration
1. public class Dialog extends Window
Java AWT Dialog Example
1. import [Link].*;
2. import [Link].*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. [Link]( new FlowLayout() );
9. Button b = new Button ("OK");
10. [Link] ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
14. [Link](false);
15. }
16. });
17. [Link]( new Label ("Click button to continue."));
18. [Link](b);
19. [Link](300,300);
20. [Link](true);
21. }
22. public static void main(String args[])
23. {
24. new DialogExample();
25. }
26. }
Java AWT Toolkit
Toolkit class is the abstract superclass of every implementation in the Abstract
Window Toolkit. Subclasses of Toolkit are used to bind various components. It
inherits Object class.
AWT Toolkit class declaration
1. public abstract class Toolkit extends Object
Java AWT Toolkit Example
1. import [Link].*;
2. public class ToolkitExample {
3. public static void main(String[] args) {
4. Toolkit t = [Link]();
5. [Link]("Screen resolution = " + [Link](
));
6. Dimension d = [Link]();
7. [Link]("Screen width = " + [Link]);
8. [Link]("Screen height = " + [Link]);
9. }
10. }
Output:
Screen resolution = 96
Screen width = 1366
Screen height = 768
Java AWT Toolkit Example: beep()
1. import [Link].*;
2. public class ToolkitExample {
3. public static void main(String[] args) {
4. Frame f=new Frame("ToolkitExample");
5. Button b=new Button("beep");
6. [Link](50,100,60,30);
7. [Link](b);
8. [Link](300,300);
9. [Link](null);
10. [Link](true);
11. [Link](new ActionListener(){
12. public void actionPerformed(ActionEvent e){
13. [Link]().beep();
14. }
15. });
16. }
17. }
Java AWT Toolkit Example: Change TitleBar Icon
1. import [Link].*;
2. class ToolkitExample {
3. ToolkitExample(){
4. Frame f=new Frame();
5. Image icon = [Link]().getImage("D:\\[Link]");
6. [Link](icon);
7. [Link](null);
8. [Link](400,400);
9. [Link](true);
10. }
11. public static void main(String args[]){
12. new ToolkitExample();
13. }
14. }
Java ActionListener Interface
The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent. The ActionListener interface is found in
[Link] package. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on
the registered component.
1. public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement
the ActionListener class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
1. public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
1. [Link](instanceOfListenerclass);
3) Override the actionPerformed() method:
1. public void actionPerformed(ActionEvent e){
2. //Write the code here
3. }
Java ActionListener Example: On Button click
1. import [Link].*;
2. import [Link].*;
3. //1st step
4. public class ActionListenerExample implements ActionListener{
5. public static void main(String[] args) {
6. Frame f=new Frame("ActionListener Example");
7. final TextField tf=new TextField();
8. [Link](50,50, 150,20);
9. Button b=new Button("Click Here");
10. [Link](50,100,60,30);
11. //2nd step
12. [Link](this);
13. [Link](b);[Link](tf);
14. [Link](400,400);
15. [Link](null);
16. [Link](true);
17. }
18. //3rd step
19. public void actionPerformed(ActionEvent e){
20. [Link]("Welcome to Javatpoint.");
21. }
22. }
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It
is notified against MouseEvent. The MouseListener interface is found in
[Link] package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Java MouseListener Example
1. import [Link].*;
2. import [Link].*;
3. public class MouseListenerExample extends Frame implements Mo
useListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. [Link](20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. [Link]("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. [Link]("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. [Link]("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. [Link]("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. [Link]("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }
Java MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse.
It is notified against MouseEvent. The MouseMotionListener interface is found
in [Link] package. It has two methods.
Methods of MouseMotionListener interface
The signature of 2 methods found in MouseMotionListener interface are given
below:
1. public abstract void mouseDragged(MouseEvent e);
2. public abstract void mouseMoved(MouseEvent e);
Java MouseMotionListener Example
1. import [Link].*;
2. import [Link].*;
3. public class MouseMotionListenerExample extends Frame implem
ents MouseMotionListener{
4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. [Link]([Link]);
14. [Link]([Link](),[Link](),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }
Java ItemListener Interface
The Java ItemListener is notified whenever you click on the checkbox. It is
notified against ItemEvent. The ItemListener interface is found in
[Link] package. It has only one method: itemStateChanged().
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click
or unclick on the registered checkbox component.
1. public abstract void itemStateChanged(ItemEvent e);
Java ItemListener Example
1. import [Link].*;
2. import [Link].*;
3. public class ItemListenerExample implements ItemListener{
4. Checkbox checkBox1,checkBox2;
5. Label label;
6. ItemListenerExample(){
7. Frame f= new Frame("CheckBox Example");
8. label = new Label();
9. [Link]([Link]);
10. [Link](400,100);
11. checkBox1 = new Checkbox("C++");
12. [Link](100,100, 50,50);
13. checkBox2 = new Checkbox("Java");
14. [Link](100,150, 50,50);
15. [Link](checkBox1); [Link](checkBox2); [Link](label);
16. [Link](this);
17. [Link](this);
18. [Link](400,400);
19. [Link](null);
20. [Link](true);
21. }
22. public void itemStateChanged(ItemEvent e) {
23. if([Link]()==checkBox1)
24. [Link]("C++ Checkbox: "
25. + ([Link]()==1?"checked":"unchecked"));
26. if([Link]()==checkBox2)
27. [Link]("Java Checkbox: "
28. + ([Link]()==1?"checked":"unchecked"));
29. }
30. public static void main(String args[])
31. {
32. new ItemListenerExample();
33. }
34. }
35. Java Swing Tutorial
36. Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit)
API and entirely written in java.
37. Unlike AWT, Java Swing provides platform-independent and lightweight components.
38. The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
39.
40. Difference between AWT and Swing
41. There are many differences between java awt and swing that are given below.
42. No. Java AWT Java Swing
1) AWT components Java swing components
are platform-dependent. are platform-independent.
AWT components Swing components
2)
are heavyweight. are lightweight.
AWT doesn't support Swing supports pluggable
3)
pluggable look and feel. look and feel.
Swing provides more
powerful components such
AWT provides less
4) as tables, lists, scrollpanes,
components than Swing.
colorchooser, tabbedpane
etc.
AWT doesn't follows
MVC(Model View Controller)
where model represents
5) data, view represents Swing follows MVC.
presentation and controller
acts as an interface between
model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding
it on the JFrame object inside the main() method.
File: [Link]
1. import [Link].*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. [Link](130,100,100, 40);//x axis, y axis, width, height
8.
9. [Link](b);//adding button in JFrame
10.
11. [Link](400,500);//400 width and 500 height
12. [Link](null);//using no layout managers
13. [Link](true);//making the frame visible
14. }
15. }
o JButton class
o JRadioButton class
o JTextArea class
o JComboBox class
o JTable class
o JColorChooser class
o JProgressBar class
o JSlider class
o Digital Watch
o Graphics in swing
o Displaying image
o Edit menu code for Notepad
o OpenDialog Box
o Notepad
o Puzzle Game
o Pic Puzzle Game
o Tic Tac Toe Game
o BorderLayout
o GridLayout
o FlowLayout
o CardLayout