Core Java Notes
Core Java Notes
Unit 1
Introduction to Java
Java is a programming language and a platform. Java is a high level,
robust, object oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of
Oracle) in the year 1995. James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the Oak name to Java.
Platform: Any hardware or software environment in which a program runs,
is known as a platform. Since Java has a runtime environment (JRE) and
API, it is called a platform.
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.
2) Initially 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
next → ← prev
History of Java
1. History of Java
2. Java Version History
The history of Java is very interesting. Java was originally designed for
interactive television, but it was too advanced technology for the digital
cable television industry
at the time. The history of Java starts with the Green Team. Java team
members (also known as Green Team), initiated this project to develop a
language for digital devices such as set-top boxes, televisions, etc.
However, it was suited for internet programming. Later, Java technology
was incorporated by Netscape.
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.
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 uzzwords.
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 Robust simply means strong. Java is robust because:
It uses strong memory management. There is a lack of pointers that avoids
security problems.
There is automatic garbage collection in java 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.
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 dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++. Java supports dynamic compilation and
automatic memory management (garbage collection).
Java OOPs Concepts
1. Object-Oriented Programming
2. Advantage of OOPs over Procedure-oriented programming language
3. Difference between Object-oriented and Object-based programming
language.
In this page, we will learn about the basics of OOPs. Object-Oriented
Programming is a paradigm that provides many concepts, such as
inheritance, data binding, polymorphism, etc.
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:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
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
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.
Inheritance
When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance.It provides code reusability. It is used to
achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc. In Java, we use method
overloading and method overriding to achieve polymorphism. Another
example can be to speak something; for example, a cat speaks meow, dog
barks woof,etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example phone call, we won't know the internal processing. In Java,
we use abstract class and interface to achieve abstraction.
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.
Java Environment and Java Tools
Java environments include a number of development tools, classes and
methods. The development tools are part of the system known as Java
Development Kit (JDK) and the classes and methods are part of the Java
Standard Library(ISL), also known as the Application Programming
Interface(API).
Java Development Kit The java development kit comes with a collection
softools that are used for developing and running javaprogram. They
include
1) Applet viewer (For viewing Java applets): A pre- created applet can be
viewed using applet viewer. It enables us to run Java applets (without
actually usinga Java-compatible browser). Following command is used for
executing java applets:
C:\>appletviewer <URL of the.html file>
2) javac (Java Compiler): A java program can be created by using any text
editor (i.e. notepad/word pad /edit pad) and save file with .java extension
(filename.java). The java compiler, translates filename.java source code to
import java.io.*;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Steps:
Save this file as Simple.java
To compile: javac Simple.java
To execute: java Simple
Compilation Flow:
When we compile Java program using javac tool, java compiler converts
the source code into byte code.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
import keyword is used to import a package, class or interface.
import java package into a class, we need to use java import keyword
which is used to access package and its classes into the java program.
Use import to access built-in and user-defined packages into your java
source file
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. Application Programming Interface
(API).
The java Standard Library (JSL) or API includes hundreds of classes and
methods several unctional packages. Most commonly used packages are:
i. Language support package: A collection of classes and methods required
for implementing basic features of Java.
2) Utilities package: A collection of classes to provide utility functions
such as date and time
and static. There are two types of data types in Java: primitive and non-
primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it
is a name of memory location. It is a combination of "vary + able" that
means its value can be changed.
1. int data=50;//Here data is variable Types of Variables
There are three types of variables in Java:
local variable
instance variable
static variable
1) Local Variable
A variable declared inside the body of the method is called local
variable.
Local variable can be declared in the method, Constructor or block
Local variables are visible only within the declared method
constructor or block
You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
Access modifiers cannot be used with local variable
Let us take an example in which we take local variable to explain it. Here,
age is a local variable. This variable is defined under putAge() method and
its scope is limited to this method only:
2) Instance Variable
A variable declared inside the class but outside the body of the
method, is called instance variable.
It is not declared as static.
It is called instance variable because its value is instance specific and
is not shared among instances.
Instance variable can be accessed object with reference variable
which contains object
import java.io.*;
public class Employee {
// this instance variable is visible for any child class.public
String name;
//salary variable is visible in Employee class only.private
double salary;
// The name variable is assigned in the constructor.public
Employee (String empName)
{
name = empName;
}
// The salary variable is assigned a value.public
void setSalary(double empSal)
{
salary = empSal;
}
// This method prints the employee details.public void
printEmp()
{
System.out.println("name : " + name );System.out.println("salary :"
+ salary);
}
{
//salary variable is a private static variableprivate
static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";public
static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
Output
This will produce the following result −
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant
should be accessed as Employee.DEPARTMENT
void method(){
int n=90;//local variable6.
}
}
//end of class
Java Variable Example: Add Two Numbers
class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c); 7.
}
}
Output: 20
Data Types
Data Type determines type of value that a variable can hold The main
purpose of data types in java is to determine what kind of value we can
stored in to the variable. Data types specify the different sizes and values
that can be stored in the variable. There are two types of data types in
Java:
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.
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Decision-Making statements:
1) If Statement:
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block
of code if the expression evaluates to true.
if(condition)
{
statement 1; //executes when condition is true
}
Student.java
Student.java
}
}
Output:
x + y is greater than 20
2) if-else statement
Syntax:
if(condition)
{
statement 1; //executes when condition is true
}
Else
{
statement 2; //executes when condition is false
}
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
Student.java
Output:
Delhi
4. Nested 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
} }
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
Switch Statement:
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Student.java
default:
System.out.println(num);
}
}
}
Output:
While using switch statements, we must notice that the case expression
will be of the same type as the variable. However, it will also be a constant
value. The switch permits only int, string, and Enum type variables to be
used.
Loop Statements
1. for loop
2. while loop
3. do-while loop
In Java, for loop. 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
Output:
The single-line comment is used to comment only one line of the code. It
is the widely used and easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front
of // is not executed by Java.
Syntax:
CommentExample1.java
Output:
10
Multi-line comments are placed between /* and */. Any text between /*
and */ is not executed by Java.
Syntax:
/*
This
is
multi line comment */
UNIT 2
Classes and Objects
An object in Java is the physical as well as a logical entity, whereas, a
class in Java is a logical entity only.
An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system.
Object Definitions:
class in Java
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
class <class_name>
{
field;
method;
}
In this example, we have created a Student class which has two data
members id and name. We are creating the object of the Student class by
new keyword and printing the object's value.
File: Student.java
class Student
{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
OUTPUT
0
Null
Constructors in Java
Every time an object is created using the new() keyword, at least one
constructor is called.
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It
will be invoked at the time of object creation
1. Output:
2. Bike is created
Parameterized Constructor
In this example, we have created the constructor of Student class that have
two parameters. We can have any number of parameters in the constructor.
class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);
}
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.
11 Karan
222 Aryan
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);
}
}
OutPut:
y is:40000.0
Bonus of programmer is:10000
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
Single Inheritance
.... methods
}
Java uses the keyword “extends” to create a new class(derived class) from
the existing class(base class). The term “extends” means to increase the
functionality as the derived class can reuse the methods and fields of the
base class, and along with this, new methods and fields can also be defined
in the derived class, hence increasing the functionality.
Code to illustrate Single Inheritance in Java
class Employee {
void salary() {
System.out.println("Salary= 200000");
void bonus() {
System.out.println("Bonus=50000");
class single_inheritance {
}
Output:
Salary= 200000
Bonus=50000
Multilevel Inheritance
//Superclass box...
class Box {
width = w;
height = h;
depth = d;
// Volume calculation...
double volume() {
// Sub class - 1
weight = m;
// Sub class - 2
double cost;
cost = c;
}}
double vol;
vol = shipment1.volume();
System.out.println();
vol = shipment2.volume();
Output
Interface
Now you may be wondering how using an interface solves the problem we
were facing before.
To understand the reason, let us consider our previous example, but we’ll
use an interface instead of a class this time.
System.out.println("Hello");
class Main
obj.text();
Output:
Hello
The abstract class in Java cannot be instantiated (we cannot create objects
of abstract classes). We use the abstract keyword to declare an abstract
class. For example,
...
// throws an error
An abstract class can have both the regular methods and abstract methods.
For example,
// abstract method
// regular method
void method2() {
// error
class Language {
// abstract method
obj.display();
Output
Method overloading allows the method to have the same name which
differs on the basis of arguments or the argument types. It can be related to
compile-time polymorphism. Following are a few pointers that we have to
keep in mind while overloading methods in Java.
return (a / b); }
ob.div(10 , 2);
ob.div(10, 2 , 3);
Output: 5
return 100;
return "edureka";
System.out.println(func(1));
System.out.println(func(1,3));
Output: 100
Edureka
UNIT 3
Collection
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array
to store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements stored
in the ArrayList class can be randomly accessed. Consider the following
example.
import java.util.*;
class TestJavaCollection1
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
Iterator itr=list.iterator();
while(itr.hasNext())
System.out.println(itr.next());
} }
Output:
Ravi
Vijay
Ravi
Ajay
Vector
import java.util.*;
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Output:
Ayush
Amit
Ashish
Garima
HashSet
Learn more
import java.util.*;
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext())
System.out.println(itr.next());
} } }
Output:
Vijay
Ravi
Ajay
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage.
Like HashSet, TreeSet also contains unique elements. However, the access
and retrieval time of TreeSet is quite fast. The elements in TreeSet stored
in ascending order.
import java.util.*;
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext())
System.out.println(itr.next());
} } }
Output:
Ajay
Ravi
Vijay
Hashtable class
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Map Interface
A map contains values on the basis of key, i.e. key and value pair. Each
key and value pair is known as an entry. A Map contains unique keys.A
Map is useful if you have to search, update or delete elements on the basis
of a key.
import java.util.*;
HashMap<Integer,String> map=new
HashMap<Integer,String>();//Creating HashMap
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
OutPut:
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes
UNIT 4
statement 1;
statement 2;
statement 3;
statement 4;
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
2) Unchecked Exception
3) Error
Java provides five keywords that are used to handle the exception.
The following table describes each.
Keyword Description
JavaExceptionExample.java
try
int data=100/0;
catch(ArithmeticException e)
System.out.println(e);
Output:
1. int a=50/0;//ArithmeticException
String s=null;
System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
a[10]=50; //ArrayIndexOutOfBoundsException
Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
Try
catch(Exception_class_Name ref){}
Try
finally{}
The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
Example 1
TryCatchExample1.java
Output:
There might be 100 lines of code after the exception. If the exception
is not handled, all the code below the exception won't be executed.
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
Example 2
TryCatchExample2.java
try
catch(ArithmeticException e)
System.out.println(e);
Output:
java.lang.ArithmeticException: / by zero
Example 3
In this example, we also kept the code in a try block that will not
throw an exception.
TryCatchExample3.java
try
catch(ArithmeticException e)
System.out.println(e);
Output:
java.lang.ArithmeticException: / by zero
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.
At a time only one exception occurs and at a time only one catch
block is executed.
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
MultipleCatchBlock1.java
Try
a[5]=30/0;
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
catch(Exception e)
Output:
10 Sec
23.2M
443
Example 2
MultipleCatchBlock2.java
try{
System.out.println(a[10]);
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
catch(Exception e)
Output:
Let's see the different cases where Java finally block can be used.
TestFinallyBlock.java
class TestFinallyBlock
Try
int data=25/5;
System.out.println(data);
catch(NullPointerException e)
System.out.println(e);
finally
Output:
TestThrow1.java
if(age<18)
else {
//main method
validate(13);
Output:
TestThrow2.java
import java.io.*;
//main method
try
method();
catch (FileNotFoundException e)
e.printStackTrace();
Output:
TestThrow3.java
super(str);
try
System.out.println(ude.getMessage());
Output:
File handling
Stream
Byte Stream Byte Stream is mainly involved with byte data. A file
handling process with a byte stream is a process in which an input is
provided and executed with the byte data.
Character Stream
Type
Description
8. length() Long The length() method is used to get the size of the
file in bytes.
9. list() String[] The list() method is used to get an array of the files
available in the directory.
10. mkdir() Boolean The mkdir() method is used for creating a new
directory.
File Operations
Create a File
Get File Information
Write to a File
Read from a File
Delete a File
Create a File
true when it successfully creates a new file and returns false when
the file already exists.
CreateFile.java
import java.io.File;
import java.io.IOException;
class CreateFile
Try
if (f0.createNewFile())
else {
exception.printStackTrace();
Explanation:
In the above code, we import the File and IOException class for
performing file operation and handling errors, respectively. We
create the f0 object of the File class and specify the location of the
directory where we want to create a file. In the try block, we call the
createNewFile() method through the f0 object to create a new file in
the specified location. If the method returns false, it will jump to the
else section.
of the file.
FileInfo.java
import java.io.File;
class FileInfo
if (f0.exists())
else {
Output:
Description:
the file.
3. We check whether we can write data into a file or not using the
canWrite()
4. We check whether we can read the data of the file or not using the
canRead()
Write to a File
class and its write() method together. We need to close the stream
using the close() method to retrieve the allocated resources.
WriteToFile.java
import java.io.FileWriter;
import java.io.IOException;
class WriteToFile
try
fwrite.close();
catch (IOException e)
e.printStackTrace();
Output:
Explanation:
After that, we call the close() method of the FileWriter class to close
the file stream.
After writing the content and closing the stream, we print a custom
message.
If we get any error in the try section, it jumps to the catch block. In
the catch block, we handle the IOException and print a custom
message.
ReadFromFile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class ReadFromFile
try
while (dataReader.hasNextLine())
System.out.println(fileData);
dataReader.close();
exception.printStackTrace();
Output:
Expalnation:
Delete a File
DeleteFile.java
import java.io.File;
class DeleteFile
if (f0.delete())
else {
Output:
Explanation:
In the above code, we import the File class and create a class
DeleteFile. In the main() method of the class, we create f0 object of
the file which we want to delete. In the if statement, we call the
delete() method of the file using the f0 object. If the delete() method
returns true, we print the success custom message. Otherwise, it
jumps to the else section where we print the unsuccessful custom
message. All the above-mentioned operations are used to read, write,
delete, and create file programmatically.
UNIT 5
Advantage of Applet
Drawback of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
public void init(): is used to initialized the Applet. It is invoked only once.
public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
java.awt.Component class
By html file.
To execute the applet by html file, create an applet and compile it. After
that create an html file and place the applet code in html file. Now click
the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome",150,150);
myapplet.html
<html>
<body>
</applet>
</body>
</html>
//First.java
import java.applet.Applet;
import java.awt.Graphics;
g.drawString("welcome to applet",150,150);
/*
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
import java.applet.Applet;
import java.awt.*;
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
AWT
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.
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.
AWTExample1.java
import java.awt.*;
AWTExample1()
// creating a button
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
// no layout manager
setLayout(null);
setVisible(true);
// main method
Output:
Event Handling
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
Button
MenuItem
TextField
TextArea
Checkbox
Choice
List
import java.awt.*;
import java.awt.event.*;
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
b.setBounds(100,120,80,30);
//register listener
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
tf.setText("Welcome");
new AEvent();
1 LayoutManagers
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
S Java BorderLayout
FileName: Border.java
import java.awt.*;
import javax.swing.*;
// creating buttons
JButton b1 = new JButton("NORTH");; //the button will be labeled as NORTH
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
wings Rahul
102 SS
101 Swing
The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
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: FirstSwingExample.java
import javax.swing.*;
JComponent
The JComponent class is the base class of all Swing components except
top-level containers. Swing components whose names begin with "J" are
descendants of the JComponent class. For example, JButton, JScrollPane,
JPanel, JTable etc. But, JFrame and JDialog don't inherit JComponent
class because they are the child of top-level containers.
The JComponent class extends the Container class which itself extends
Component. The Container class has support for adding components to the
container.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
g.setColor(Color.green);
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(com);
frame.setVisible(true);
Output:
Vijay
100 Amit