java assignment bca
java assignment bca
As the name suggests, Object-Oriented Programming or OOPs 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 assigned by you. Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.
Let us discuss prerequisites by polishing concepts of method declaration and message passing. Starting off with the method
declaration, it consists of six components:
Access Modifier:
Defines the access type of the method i.e. from where it can be accessed in your application. In Java, there are 4 types of access
specifiers:
public:
Accessible in all classes in your application.
protected:
Accessible within the package in which it is defined and in its subclass(es) (including subclasses declared outside the package).
private:
Accessible only within the class in which it is defined.
default (declared/defined without using any modifier):
Accessible within the same class and package within which its class is defined.
Method Name:
The rules for field names apply to method names as well, but the convention is a little different.
Parameter list:
Comma-separated list of the input parameters that are defined, preceded by their data type, within the enclosed parentheses.
If there are no parameters, you must use empty parentheses ().
Exception list:
The exceptions you expect the method to throw. You can specify these exception(s).
Method body: It is the block of code, enclosed between braces, that you need to execute to perform your intended operations.
Message Passing:
Objects communicate with one another by sending and receiving information to each other. A message for an object is a
request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired
results. Message passing involves specifying the name of the object, the name of the function and the information to be sent.
Class
Object
Method and method passing
Pillars of OOPs
Abstraction
Encapsulation
Inheritance
Polymorphism
Compile-time polymorphism
Runtime polymorphism
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods
that are common to all objects of one type. Using classes, you can create multiple objects with the same behavior instead of
writing their code multiple times. This includes classes for objects occurring more than once in your code. In general, class
declarations can include these components in order:
Modifiers:
A class can be public or have default access (Refer to this for details).
Class name: The class name should begin with the initial letter capitalized by convention.
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements.
A class can implement more than one interface.
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
Identity: It is a unique name given to an object that enables it to interact with other objects.
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.
Output
Employee name is: Rathod Avinash
Employee CTC is: 10000.0
Let us now discuss the 4 pillars of OOPs:
Pillar 1: Abstraction
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();
}
Pillar 2: 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.
Demonstration of Encapsulation:
//Employee class contains private data called employee id and employee name
class Employee {
private int empid;
private String ename;
}
Pillar 3: Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by which one class is
allowed to inherit the features (fields and methods) of another class. We are achieving inheritance by using extends keyword.
Inheritance is also known as “is-a” relationship.
Superclass: The class whose features are inherited is known as superclass (also known as base or parent class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or child class). The
subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a
class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Demonstration of Inheritance :
Pillar 4: Polymorphism
It refers to the ability of object-oriented programming languages to differentiate between entities with the same name
efficiently. This is done by Java with the help of the signature and declaration of these entities. The ability to appear in many
forms is called polymorphism.
E.g.
sleep(1000) //millis
sleep(1000,2000) //millis,nanos
Overloading
Overriding
Example
// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output
30
60
31.0
Mainly used for C++ is mainly used for system Java is mainly used for application programming. It is
programming. widely used in Windows-based, web-based, enterprise,
and mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpreter for
applications programming. It was an printing systems but later extended as a support
extension of the C programming network computing. It was designed to be easy to use
language. and accessible to a broader audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance through
inheritance class. It can be achieved by using interfaces in java.
Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
Pointers C++ supports pointers. You can write a Java supports pointer internally. However, you can't
pointer program in C++. write the pointer program in java. It means java has
restricted pointer support in java.
Compiler and C++ uses compiler only. C++ is Java uses both compiler and interpreter. Java source
Interpreter compiled and run using the compiler code is converted into bytecode at compilation time.
which converts source code into The interpreter executes this bytecode at runtime and
machine code so, C++ is platform produces output. Java is interpreted that is why it is
dependent. platform-independent.
Call by Value and C++ supports both call by value and Java supports call by value only. There is no call by
Call by reference call by reference. reference in java.
Structure and C++ supports structures and unions. Java doesn't support structures and unions.
Union
Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party libraries
for thread support.
Documentation C++ doesn't support documentation Java supports documentation comment (/** ... */) to
comment comments. create documentation for java source code.
Virtual Keyword C++ supports virtual keyword so that Java has no virtual keyword. We can override all non-
we can decide whether or not to static methods by default. In other words, non-static
override a function. methods are virtual by default.
unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator that
shift >>> fills zero at the top for the negative numbers. For
positive numbers, it works same like >> operator.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s.
James Gosling - founder of java
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given
significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun
engineers called Green Team.
ADVERTISEMENT
2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the team
members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name
was chosen by James Gosling while having a cup of coffee nearby his office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in
1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to
the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications,
cards, etc. Each new version adds new features in Java
Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure programming
language. Apart from this, there are also some excellent features which play an important role in the popularity of this language.
The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is
a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing
some rules.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
Java is platform independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in
which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other
hardware-based platforms. It has two components:
Runtime Environment
API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled
by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple
platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
Robust
The English mining of Robust is strong. Java is robust because:
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being
used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is
fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the
internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports
functions from its native languages, i.e., C and C++.
ADVERTISEMENT
Java supports dynamic compilation and automatic memory management (garbage collection).
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types
available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need to
declare variable's type and name.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a
byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example:
The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an
integer.
Example:
Example:
Example:
Example:
float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is
generally used for decimal values just like float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:
double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).The char data type is used to store characters.
Example:
We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See the brief overview of
JVM here.
If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see the differences
between the JDK, JRE, and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a
specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the
configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
Backward Skip 10sPlay VideoForward Skip 10s
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of
software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java
Application.
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Operator Type Category Precedence
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Output:
22
21
Java Unary Operator Example: ~ and !
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.
40
80
80
240
2
5
2
5
5
-5
1073741819
The bitwise & operator always checks both conditions whether first condition is true or false.
false
False
false
10
false
11
The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the
first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
true
true
true
10
true
11
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the
only conditional operator which takes three operands.
2
Another Example:
Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its
left.
14
16
13
9
18
9
Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code. These are
predefined words by Java so they cannot be used as a variable or object name or class name.
abstract:
Java abstract keyword is used to declare an abstract class. An abstract class can provide the implementation of the interface. It
can have abstract and non-abstract methods.
boolean:
Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
break:
Java break keyword is used to break the loop or switch statement. It breaks the current flow of the program at specified
conditions.
byte:
Java byte keyword is used to declare a variable that can hold 8-bit data values.
case:
Java case keyword is used with the switch statements to mark blocks of text.
catch:
Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
char:
Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
class:
Java class keyword is used to declare a class.
continue:
Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code
at the specified condition.
default:
Java default keyword is used to specify the default block of code in a switch statement.
do:
Java do keyword is used in the control statement to declare a loop. It can iterate a part of the program several times.
double: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.
else: Java else keyword is used to indicate the alternative branches in an if statement.
enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a
variable. It is used to restrict the user from updating the value of the variable.
finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always
executed whether an exception is handled or not.
float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions
repeatedly when some condition becomes true. If the number of iteration is fixed, it is recommended to use for loop.
if: Java if keyword tests the condition. It executes the if block if the condition is true.
import: Java import keyword makes classes and interfaces available and accessible to the current source code.
instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an
interface.
int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
package: Java package keyword is used to declare a Java package that includes the classes.
private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the
class in which it is declared.
protected: Java protected keyword is an access modifier. It can be accessible within the package and outside the package but
through inheritance only. It can't be applied with the class.
public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest
scope among all other modifiers.
return: Java return keyword is used to return from a method when its execution is complete.
short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is mainly
used for memory management.
strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
super: Java super keyword is a reference variable that is used to refer to parent class objects. It can be used to invoke the
immediate parent class method.
switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement
tests the equality of a variable against multiple values.
synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
this: Java this keyword can be used to refer the current object in a method or constructor.
throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly
used to throw custom exceptions. It is followed by an instance.
throws: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated with throws.
transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either
catch or finally block.
void: Java void keyword is used to specify that a method does not have a return value.
volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of
iteration is not fixed, it is recommended to use the while loop.
Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which
they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called
control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific
condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-
statements given below.
Play Video
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the
program to enter a block of code if the expression evaluates to true.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is
executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
Student.java
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is
the chain of if-else statements that create a decision tree where the program may enter in the block of code where the
condition is true. We can also define an else statement at the end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
Student.java
Delhi
4) Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Student.java
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi
5) Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called
cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead
of if-else-if statements. It also enhances the readability of the program.
The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the value of expression. It is optional.
Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it
will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it
will also be a constant value. The switch permits only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However,
loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions
depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition
checking time.
for loop
while loop
do-while loop
Let's understand the loop statements one by one.
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to
execute the block of code.
Calculation.java
Calculation.java
Java
C
C++
Python
JavaScript
The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the number of
iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement
doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then
the loop body will be executed; otherwise, the statements after the loop will be executed.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Calculation .java
0
2
4
6
8
10
The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of
iteration is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is
given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Calculation.java
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements
transfer the execution control to the other part of the program. There are two types of jump statements in Java, i.e., break and
continue.
As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the
next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch
statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
Output:
0
1
2
3
4
5
6
}
}
}
Output:
0
1
2
3
4
5
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop and
jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods,
blocks and nested classes. The static keyword belongs to the class than an instance of the class.
The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example,
the company name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
Play Video
Output:
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance
variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is
incremented, it won't reflect other objects. So each object will have the value 1 in the count variable.
Counter(){
count++;//incrementing value
System.out.println(count);
}
Output:
1
1
1
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static
variable, it will retain its value.
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
1
2
3
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Example of static method
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
class Calculate{
static int cube(int x){
return x*x*x;
}
Output:125
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
class A{
int a=40;//non static
Output:
static block is invoked
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
variable
Method
Class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:
Compile Time Error
Output:
Compile Time Error
Output:
Compile Time Error
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the
access level of fields, constructors, methods, and class by applying the access modifier on it.
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
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.
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.
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.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going
to learn the access modifiers only.
1) Private
2)
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data member and private method. We are
accessing these private members from outside the class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot
be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and
public.
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A
class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed
from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
Hello
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
Inheritance in Java
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.
Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child
class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a
parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is
to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
Java Inheritance Example
Inheritance in Java
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two
classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
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.
When one class inherits multiple classes, it is known as multiple inheritance. For 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: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating…
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: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
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.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating…
Multithreading in Java
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.
1) It doesn't block the user because threads are independent and you can perform multiple operations at the same 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:
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.
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.
Runnable:
A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be
ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving
the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for
a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so
that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to
run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change
in the state of a thread is from runnable to running and again back to runnable.
Blocked or Waiting:
Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the
waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same time, the
other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait for thread B to use
the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform any execution and thus
never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The main thread
then waits for the child threads to complete their tasks. When the child threads complete their job, a notification is sent to the
main thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine which
thread to choose and which one to reject, and the chosen thread is then given the opportunity to run.
Timed Waiting:
Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the critical section of a code and is
not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever, which leads to
starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific
span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The
sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution
from when it has left earlier.
Terminated:
A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one
can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.
In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java
provides the constants ENUM to represent the state of a thread. These constants are:
sleep
join with timeout
wait with timeout
parkUntil
parkNanos
public static final Thread.State TERMINATED
It represents the final state of a thread that is terminated or dead. A terminated thread means it has completed its execution.
The following Java program shows some of the states of a thread defined above.
FileName: ThreadState.java
// ABC class implements the interface Runnable
class ABC implements Runnable
{
public void run()
{
// try-catch block
try
{
// moving thread t2 to the state timed waiting
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+ ThreadState.t1.getState());
// try-catch block
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
// main method
public static void main(String argvs[])
{
// creating an object of the class ThreadState
obj = new ThreadState();
t1 = new Thread(obj);
// thread t1 is spawned
// The thread t1 is currently in the NEW state.
System.out.println("The state of thread t1 after spawning it - " + t1.getState());
System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState() );
}
Output:
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
package in java
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
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).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
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.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
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. java.util and java.sql packages contain Date class.
Note: Sequence of the program must be package then import then class.
sequence of package
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String,
Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.
Output:
Hello subpackage
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.
Output:
Welcome to package
There are two ways to load the class files temporary and permanent.
Temporary
By setting the classpath in the command prompt
By -classpath switch
Permanent
By setting the classpath in the environment variables
By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.
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.
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:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
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.
The java.lang.Throwable 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:
Checked Exception
Unchecked Exception
Error
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.
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.
JavaExceptionExample.java
Output:
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
String s=null;
System.out.println(s.length());//NullPointerException
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the
program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating our own
Exception is known as a custom exception or user-defined exception. Basically, Java custom exceptions are used to customize
the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.
For example, MyException in the below code extends the Exception class.
Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()”
function on the object created.
Output
Caught
GeeksGeeks
In the above code, the constructor of MyException requires a string as its argument. The string is passed to the parent class
Exception’s constructor using super(). The constructor of the Exception class can also be called without a parameter and the call
to super is not mandatory.
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in Java.
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).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating API components like
TextField, ChechBox, button, etc.
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.
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.
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:
Window
Panel
Frame
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.
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager Defines the layout manager for the component.
m)
public void setVisible(boolean status) Changes the visibility of the component, by default
false.
To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT.
AWTExample1.java
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example that sets the position of the awt
button.
Output:
AWTExample2.java
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// no layout
f.setLayout(null);
// main method
public static void main(String args[]) {
Output:
The object of JLabel 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 an application but a user cannot edit it directly. It inherits JComponent class.
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The application result in
some action when the button is pushed. It inherits AbstractButton class.
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:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
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.
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.
CharSequence in Java
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For
mutable strings, you can use StringBuffer and StringBuilder classes.
By string literal
By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
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:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in
string constant pool that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool,
it will not create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
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).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in
the string constant pool. The variable s will refer to the object in a heap (non-pool).
StringExample.java
Output:
java
strings
Example
The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on console using
println() method.