core java
core java
Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform.
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its
widespread popularity, multiple configurations were built to suit various types of platforms. For
example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box
projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office,
also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random
words.
Features of Java
• Simple
• Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, 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 incorporates both data and behavior.
• Object-oriented programming (OOPs) is a methodology that simplifies software
Platform Independent
• ava 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 the top of other hardware-based platforms. It has two
components:
• Secured
• Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
• No explicit pointer
Robust
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
• Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
• 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.
operators
Operator Type Category Precedence
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
What happen complie time.
Complier
Java code Byte code
How to run program
Code file
classloader
Bytecodeverifier
Interpreter
Runtime
Hardware
Java I/O
• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
• Stream
• A stream is a sequence of data. In Java, a stream is composed of bytes. It's called
a stream because it is like a stream of water that continues to flow.
• In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
• 1) System.out: standard output stream
• 2) System.in: standard input stream
• 3) System.err: standard error stream
Java BufferedReader Class
• Java BufferedReader class is used to read the text from a character-based input
stream. It can be used to read data line by line by readLine() method. It makes the
performance fast. It inherits Reader class.
Constructor Description
BufferedReader(Reader rd, int size) It is used to create a buffered character input stream
that uses the specified size for an input buffer.
public static void main(String[] args)
• Public
• It is an Access Modifier, which defines who can access this Method. Public means
that this Method will be accessible by any Class(If other Classes can access this
Class.).
• Static
• Static is a keyword which identifies the class related thing. It means the given
Method or variable is not instance related but Class related. It can be accessed
without creating the instance of a Class.
• Void
• Is used to define the Return Type of the Method. It defines what the method can
return. Void means the Method will not return any value.
main
• Main ss the name of the Method. This Method name is searched by JVM as a starting point for an
application with a particular signature only.
• String args[] / String… args
• It is the parameter to the main Method. Argument name could be anything.
Java try-catch
• Java try block
• Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
• Java try block must be followed by either catch or finally block.
• Syntax of Java try-catch
• try{
• //code that may throw exception
• }catch(Exception_class_Name ref){}
Java catch block
• Java catch block is used to handle the Exception. It must be used after the try
block only.
• You can use multiple catch block with a single try.
• The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.
• But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
Java Integer parseInt() Method
• The parseInt() method is a method of Integer class under java.lang package. There are three different types of Java
Integer parseInt () methods which can be differentiated depending on its parameter.
• These are:
• Java Integer parseInt (String s) Method
• Java Integer parseInt (String s, int radix) Method
• a Integer parseInt(CharSequence s, int beginText, int endText, int radix)
• 1. Java Integer parseInt (String s) Method
• This method parses the String argument as a signed decimal integer object. The characters in the string must be decimal
digits, except that the first character of the string may be an ASCII minus sign '-' to indicate a negative value or an
ASCII plus '+' sign to indicate a positive value. It returns the integer value which is represented by the argument in a
decimal integer.
• 2. Java Integer parseInt (String s, int radix) Method
• This method parses the String argument as a signed decimal integer object in the specified radix by the second
argument. The characters in the string must be decimal digits of the specified argument except that the first character
may be an ASCII minussign '-' to indicate a negative value or an ASCII plus sign '+' to indicate a positive value. The
resulting integer value is to be returned.
• 3. Java Integer parseInt (CharSequence s, int beginText, int endText, int radix)
• This method parses the CharSequence argument as a signed integer in the specified radix argument, beginning at the
specified beginIndex and extending to endIndex - 1. This method does not take steps to guard against the CharSequence
How to set path
• To set the temporary path of JDK, you need to follow the following steps:
• Open the command prompt
• Copy the path of the JDK/bin directory
• Write in command prompt: set path=copied_path
• Java If-else Statement
• The Java if statement is used to test the condition. It checks boolean con
• dition: true or false. There are various types of if statement in java.
• if(condition){
• //code to be executed
•}
Java Nested if statement
• The nested if statement represents the if block within another if block. Here, the
inner if block condition executes only when outer if block condition is true.
• if(condition)
•{
• //code to be executed
• if(condition)
•{
• //code to be executed
• }
•}
Java Switch Statement
• The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
• switch(expression){
• case value1:
• //code to be executed;
• break; //optional
• case value2:
• //code to be executed;
• break; //optional
• ......
•
• default:
• code to be executed if all cases are not matched;
• }
Java While Loop
• The Java while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed, it is recommended to use while loop.
• Syntax:
• while(condition){
• //code to be executed
•}
• Java do-while Loop
• The Java do-while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed and you must have to execute the loop at
least once, it is recommended to use do-while loop.
• The Java do-while loop is executed at least once because condition is checked
after loop body.
Syntax
• do{
• //code to be executed
• }while(condition);
• For Loop
• We can have a name of each Java for loop. To do so, we use label before the for
loop. It is useful if we have nested for loop so that we can break/continue specific
for loop.
• for(initialization;condition;incr/decr){
• //code to be executed
•}
What is a class in Java
• A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.
• A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
• class <class_name>{
• field;
• method;
What is an object
• 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.
• An object has three characteristics:
• State:represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
• Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM
to identify each object uniquely.
Access Modifiers in java
• There are two types of modifiers in java: access modifiers and non-access
modifiers.
• The access modifiers in java specifies accessibility (scope) of a data member,
method, constructor or class.
• There are 4 types of java access modifiers:
• private
• default
• protected
• public
Java static keyword
• The static keyword in Java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than an instance of the class.
• The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested clas
• 1) Java static variable
• If you declare any variable as static, it is known as a static variable.
• 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.
2) Java static method
• 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.
• 3) Java static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.
this keyword in java
• There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
this
state
• Here is given the 6 usage of java this keyword.
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.
Constructors in 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.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
• Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Types of inheritance in java
Class A Class A
Class A
C;ass B
Class B Class c
Class B Class C
Hirechical
inheritance
• The super keyword in Java is a reference variable which is used to refer immediate
class object.
• Whenever you create the instance of subclass, an instance of parent class is create
implicitly which is referred by super reference variable.
• Usage of Java super Keyword
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
Final Keyword In Java
• 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.
Java Array
static String format(Locale l, String format, returns formatted string with given locale.
Object... args)
boolean contains(CharSequence s) returns true or false after matching the sequence of char
value.
static String join(CharSequence delimiter, C returns a joined string.
harSequence... elements)
0 boolean equals(Object another) checks the equality of string with the given object.
• Wrapper class in java provides the mechanism to convert primitive into object
and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object
and object into primitive automatically. The automatic conversion of primitive
into object is known as autoboxing and vice-versa unboxing.
• The eight classes of java.lang package are known as wrapper classes in java
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
• Autoboxing in Java is used to convert automatically convert the primitive data
types into corresponding objects.
• Unboxing in Java is reverse of Autoboxing, i.e. it converts wrapper class object
into its corresponding primitive data type.
Java Vector
• Java Vector class comes under the java.util package. The vector class implements
a growable array of objects. Like an array, it contains the component that can be
accessed using an integer index.
• Vector is very useful if we don't know the size of an array in advance or we need
one that can change the size over the lifetime of a program.
• Vector implements a dynamic array that means it can grow or shrink as required.
It is similar to the ArrayList, but with two differences-
• Vector is synchronized.
• The vector contains many legacy methods that are not the part of a collections
framework
• public class Vector<E>
• extends Object<E>
SN Constructor Description
• If you are not using any IDE, you need to follow the syntax given below:
• javac -d . directory javafilename .
• The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
• How to access package from another package?
• There are three ways to access the package from outside the package.
• import package.*;
• import package.classname;
• Types of packages in Java
• As mentioned in the beginning of this guide that we have two types of
packages in java.
1) User defined package: The package we create is called user-defined
package.
2) Built-in package: The already defined package like java.io.*,
java.lang.* etc are known as built-in packages.
Exception Handling in Java
• There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception.
According to Oracle, there are three types of exceptions:
• Checked Exception
• Unchecked Exception
• Error
• Difference between Checked and Unchecked Exceptions
• 1) Checked Exception
• The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at compile-time.
• 2) Unchecked Exception
• The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they
are checked at runtime.
• 3) Error
• Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block
where we should place exception code. The try
block must be followed by either catch or
finally. It means, we can't use try block alone.
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
important code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an
exception.
throws The "throws" keyword is used to declare
exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in
Java try-catch block
• Java try block
• Java try block is used to enclose the code that might throw an exception. It must
be used within the method.
• If an exception occurs at the particular statement of try block, the rest of the
block code will not execute. So, it is recommended not to keeping the code in try
block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
• try{
• //code that may throw an exception
• }catch(Exception_class_Name ref){}
Java catch block
• Java catch block is used to handle the Exception by declaring the type of exception within
the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare the
generated type of exception.
• The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
• Java catch multiple exceptions
• 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 theAt 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.
Java Nested try block
• The try block within a try block is known as nested try block in java. Why use
nested try block
• Sometimes a situation may arise where a part of a block may cause one error and
the entire block itself may cause another error. In such cases, exception handlers
have to be nested.
• Java finally block
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.
Java throw keyword
1) Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
an exception. exception.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
Collections in Java
• The java.io package contains nearly every class you might ever need to perform
input and output (I/O) in Java. All these streams represent an input source and an
output destination. The stream in the java.io package supports many data such as
primitives, object, localized characters, etc.
• Stream
• A stream can be defined as a sequence of data. There are two kinds of Streams −
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a destination.
• Java byte streams are used to perform input and output of 8-bit bytes. Though
there are many classes related to byte streams but the most frequently used
classes are, FileInputStream and FileOutputStream. Following is an example
which makes use of these two classes to copy an input file into an output file −
• Character Streams
• Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter. Though internally
FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
the major difference is that FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
Standard Streams
• All the programming languages provide support for standard I/O where the user's
program can take input from a keyboard and then produce an output on the
computer screen. If you are aware of C or C++ programming languages, then you
must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly,
Java provides the following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.
• Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
FileInputStream
• This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors
available.
• Following constructor takes a file name as a string to create an input stream
object to read the file −
• File f = new File("C:/java/hello");
• InputStream f = new FileInputStream(f);
• Once you have InputStream object in hand, then there is a list of helper
methods which can be used to read to stream or to do other operations on
the stream.
• This method closes the file output stream. Releases any system resources associated with the file.
Throws an IOException.
• protected void finalize()throws IOException {}
• This method cleans up the connection to the file. Ensures that the close method of this file output
stream is called when there are no more references to this stream. Throws an IOException.
• public int read(int r)throws IOException{}
• This method reads the specified byte of data from the InputStream. Returns an int. Returns the
next byte of data and -1 will be returned if it's the end of the file.
• public int read(byte[] r) throws IOException{}
• This method reads r.length bytes from the input stream into an array. Returns the total number of
bytes read. If it is the end of the file, -1 will be returned.
• public int available() throws IOException{}
• Gives the number of bytes that can be read from this file input stream. Returns an int.
FileOutputStream
• FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
• Here are two constructors which can be used to create a FileOutputStream
object.
• Following constructor takes a file name as a string to create an input stream
object to write the file −
• OutputStream f = new FileOutputStream("C:/java/hello")
• File f = new File("C:/java/hello");
• OutputStream f = new FileOutputStream(f);
• public void close() throws IOException{}
• This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
• protected void finalize()throws IOException {
• This method cleans up the connection to the file. Ensures that the close method
of this file output stream is called when there are no more references to this
stream. Throws an IOException.
• public void write(int w)throws IOException{}
• This methods writes the specified byte to the output stream.
• public void write(byte[] w)
FileReader Class
• FileReader(File file)
• This constructor creates a new FileReader, given the File to read from.
• FileReader(FileDescriptor fd)
• This constructor creates a new FileReader, given the FileDescriptor to read from.
• FileReader(String filename)
• This constructor creates a new FileReader, given the name of the file to read
from.
• This class inherits from the OutputStreamWriter class. The class is used for
writing streams of characters.
Multithreading
• A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. The following diagram shows the complete life
cycle of a thread.
Runnable
New Running
Dead Waiting
• New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the runnable
state only when another thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Thread Priorities
• Every Java thread has a priority that helps the operating system determine the
order in which threads are scheduled.
• Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
• Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and are very much platform
dependent.
Create a Thread by Implementing a Runnable
Interface
• If your class is intended to be executed as a thread then you can achieve this
by implementing a Runnable interface. You will need to follow three basic
steps −
• Step 1
• As a first step, you need to implement a run() method provided by
a Runnable interface. This method provides an entry point for the thread and
you will put your complete business logic inside this method. Following is a
simple syntax of the run() method −
• Public void run()
• Step 2
• As a second step, you will instantiate a Thread object using the following
Sleep method in java
• The sleep() method of Thread class is used to sleep a thread for the
specified amount of time.
• Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws
InterruptedException
• Thread(Runnable threadObj, String threadName);
• Where, threadObj is an instance of a class that implements
the Runnableinterface and threadName is the name given to the new
thread.
• Step 3
• Once a Thread object is created, you can start it by
calling start() method, which executes a call to run( ) method.
Following is a simple syntax of start() method −
• void start();
Create a Thread by Extending a
Thread Class
• The second way to create a thread is to create a new class that
extends Thread class using the following two simple steps. This approach
provides more flexibility in handling multiple threads created using available
methods in Thread class.
• Step 1
• You will need to override run( ) method available in Thread class. This method
provides an entry point for the thread and you will put your complete business
logic inside this method. Following is a simple syntax of run() method
• Step 2
• Once Thread object is created, you can start it by calling start() method, which
executes a call to run( ) method. Following is a simple syntax of start() method −
Thread Methods
• Thread scheduler in java is the part of the JVM that decides which thread should run.
• There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
• Only one thread at a time can run in a single process.
• The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
• Sleep method in java
• The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
• Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws InterruptedException
ThreadGroup in Java
• Daemon thread in java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads
dies, JVM terminates this thread automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
• You can see all the detail by typing the jconsole in the command prompt. The
jconsole tool provides information about the loaded classes, memory usage, running
threads etc.
• Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has no role in
life than to serve user threads.
• Its life depends on user threads.
Java Thread Pool
• Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.
• In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and
assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.
• Thread Synchronization
• When we start two or more threads within a program, there may be a situation when multiple threads try to
access the same resource and finally they can produce unforeseen result due to concurrency issues. For
example, if multiple threads try to write within a same file then they may corrupt the data because one of the
threads can override data or while one thread is opening the same file at the same time another thread might
be closing the same file.
• So there is a need to synchronize the action of multiple threads and make sure that only one thread can access
the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is
associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a
monitor.
• Java programming language provides a very handy way of creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources within this block. Following is the general form of the
synchronized statement −
Java Applet
• Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It
runs inside the browser and works at client side.
• Advantage of Applet
• There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
• Lifecycle methods for Applet:
• For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
• public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
•.
start
init destory
stop
java.awt.Component class
• Applet is mostly used in games and animation. For this purpose image is
required to be displayed. The java.awt.Graphics class provide a method
drawImage() to display the image.
• Syntax of drawImage() method:
• public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
• Other required methods of Applet class to display image:
• public URL getDocumentBase(): is used to return the URL of the
document in which applet is embedded.
• public URL getCodeBase(): is used to return the base URL.
Animation in Applet
• Applet is mostly used in games and animation. For this purpose image
is required to be moved.
• EventHandling in Applet
• As we perform event handling in AWT or Swing, we can perform it in
applet also. Let's see the simple example of event handling in applet
that prints a message by click on the button.
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, ActionListener
menu-item is selected, list-item is
double clicked
MouseEvent generated when mouse is dragged, MouseListener
moved,clicked,pressed or released
and also when it enters or exit a
component
KeyEvent generated when input is received KeyListener
from keyboard
ItemEvent generated when check-box or list item ItemListener
is clicked
TextEvent generated when value of textarea or TextListener
textfield is changed
MouseWheelEvent generated when mouse wheel is MouseWheelListener
moved
WindowEvent generated when window is activated, WindowListener
deactivated, deiconified, iconified,
ComponentEvent generated when component is hidden, ComponentEventListener
moved, resized or set visible
• We can get any information from the HTML file as a parameter. For
this purpose, Applet class provides a method named getParameter().
Syntax:
• public String getParameter(String parameterName)
Java AWT Tutorial
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
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
frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)
• Java AWT Label
• The object of Label class is a component for placing text in a container. It is used
to display a single line of read only text. The text can be changed by an
application but a user cannot edit it directly.
• Java AWT TextField
• The object of a TextField class is a text component that allows the editing of a
single line text. It inherits TextComponent class.
TextArea
• The TextArea control in AWT provide us multiline editor area. The user can type here
as much as he wants. When the text in the text area become larger than the viewable
area the scroll bar is automatically appears which help us to scroll the text up & down
and right & left.
• TextArea()
• Constructs a new text area with the empty string as text.
• TextArea(int rows, int columns)
• Constructs a new text area with the specified number of rows and columns and the
empty string as text.
• Choice
• Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.
• void add(String item)
• Adds an item to this Choice menu.
• void addItem(String item)
• Obsolete as of Java 2 platform v1.1.
• Canvas
• Canvas control represents a rectangular area where application can draw
something or can receive inputs created by user.
• CheckBox Class
• Checkbox control is used to turn an option on(true) or off(false). There is label for
each checkbox representing what the checkbox does.The state of a checkbox can
be changed by clicking on it.
CheckBoxGroup Class
• Introduction
• Canvas control represents a rectangular area where application can draw
something or can receive inputs created by user.
• Image Class
• Image control is superclass for all image classes representing graphical images.
• Scrollbar
• Scrollbar control represents a scroll bar component in order to enable user to
select from range of values.
• Dialog
• Dialog control represents a top-level window with a title and a border used to
take some form of input from the user.
Java LayoutManagers
• BorderLayout (LayoutManagers)
• The BorderLayout is used to arrange the components in five regions: north,
south, east, west and center. Each region (area) may contain one component
only. It is the default layout of frame or window. The BorderLayout provides
five constants for each region
• Java FlowLayout
• The FlowLayout is used to arrange the components in a line, one after
another (in a flow). It is the default layout of applet or panel
• Java GridLayout
• The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
Java CardLayout
• The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
• Java GridBagLayout
• The Java GridBagLayout class is used to align components vertically, horizontally
or along their baseline.
• The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells
known as its display area. Each component associates an instance of
GridBagConstraints. With the help of constraints object we arrange component's
display area on the grid. The GridBagLayout manages each component's minimum
and preferred sizes in order to determine component's size.
SWing
• Java Swing tutorial is a part of Java Foundation Classes (JFC) that
is used to create window-based applications. It is built on the top of
AWT (Abstract Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and
lightweight components.
• The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Difference between AWT and Swing
No. Java AWT Java Swing
1) AWT components are platform- Java swing components are platform-
dependent. independent.
• The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
• 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.
• There are two types of the applet -
• Applets based on the AWT(Abstract Window Toolkit) package by
extending its Applet class.
• Applets based on the Swing package by extending its JApplet class.
• Exceptions are events that occur during the execution of programs
that disrupt the normal flow of instructions (e.g. divide by zero, array
access out of bound, etc.). In Java, an exception is an object that
wraps an error event that occurred within a method and contains:
Information about the error including its type.
• A Collection is a group of individual objects represented as a single
unit. Java provides Collection Framework which defines several
classes and interfaces to ... represent a group of objects as a single
unit.
HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many Hashtable is synchronized. It is thread-safe and can be shared with many threads.
threads without proper synchronization code.
2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.
5) We can make the HashMap as synchronized by calling this code Hashtable is internally synchronized and can't be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);
volatile The variable value is always read from the main memory, not from a
specific thread's memory.
• //save as Simple.java
• package mypack;
• public class Simple{
• public static void main(String args[]){
• System.out.println("Welcome to package");
• }
• }
• How to compile java package
• If you are not using any IDE, you need to follow the syntax given below:
• java mypack.Simple]
• The super keyword in java is a reference variable that is used to refer
parent class objects. The keyword “super” came into the picture with
the concept of Inheritance. It is majorly used in the following
contexts:
• 2. Use of super with methods: This is used when we want to call
parent class method. So whenever a parent and child class have same
named methods then to resolve ambiguity we use super keyword.
This code snippet helps to understand the said usage of super
keyword.
• class Person
• {
• void message()
• {
• System.out.println("This is person class");
• }
• }
•
• /* Subclass Student */
• class Student extends Person
• {
• void message()
• {
• System.out.println("This is student class");
• void display()
• // will invoke or call current class message() method
• message();
•
• // will invoke or call parent class message() method
• super.message();
• }
• }
• /* Driver program to test */
• class Test
• {
• public static void main(String args[])
• {
• Student s = new Student();
•
• // calling display() of Student
• s.display();
• Exception handling is one of the most important feature of java
programming that allows us to handle the runtime errors caused by
exceptions. In this guide, we will learn what is an exception, types of
it, exception classes and how to handle exceptions in java with
examples.
• Exception Handling
• If an exception occurs, which has not been handled by programmer
then program execution gets terminated and a system generated
error message is shown to the user. For example look at the system
generated exception below:
• public class JavaExceptionExample{
• public static void main(String args[]){
• try{
• //code that may raise exception
• int data=100/0;
• }catch(ArithmeticException e){System.out.println(e);}
• //rest code of the program
• System.out.println("rest of the code...");
• }
• }
• public class FileCopyExample {
• try {
• FileReader fr = new FileReader("input.txt");
• BufferedReader br = new BufferedReader(fr);
• FileWriter fw = new FileWriter("output.txt", true);
• String s;
2) Both StringBuffer and StringBuilder represents mutable String which means you can add/remove
characters, substring without creating new objects.
4) Both StringBuilder and StringBuffer doesn't override equals() and hashCode() method because
they are mutable and not intended to be used as a key in hash-based collection classes e.g.
HashMap, Hashtable, and HashSet.
5) StringBuffer is synchronized which means all method which modifies the internal data of
StringBuffer is synchronized e.g. append(), insert() and delete(). On contrary, StringBuilder is not
synchronized.
6) Because of synchronization StringBuffer is considered thread safe e.g. multiple threads can call
its method without compromising internal data structure but StringBuilder is not synchronized
hence not thread safe
Read more:
https://javarevisited.blogspot.com/2017/08/10-differences-between-stringbuffer-and-StringBuilde
r-in-java.html#ixzz64UWwkn23
• Ex2
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because
has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including the following −
•An applet is a Java class that extends the java.applet.Applet class.
•A main() method is not invoked on an applet, and an applet class will not define main().
•Applets are designed to be embedded within an HTML page.
•When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.
•A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime
environment.
• Life Cycle of an Applet
• Four methods in the Applet class gives you the framework on which you build any serious applet −
• init − This method is intended for whatever initialization is needed for your applet. It is called after
the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It is also called
whenever the user returns to the page containing the applet after having gone off to other pages.
• stop − This method is automatically called when the user moves off the page on which the applet
sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally. Because applets are
meant to live on an HTML page, you should not normally leave resources behind after a user
leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
• Abstract class in Java
• A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
• Before learning the Java abstract class, let's understand the abstraction in Java first.
• Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
• Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.
• Abstraction lets you focus on what the object does instead of how it does it.
• Abstract class in Java
• A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
• Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• Abstract Method in Java
• A method which is declared as abstract and does not have implementation is known as an abstract
method.
• abstract class Bike{
• abstract void run();
• }
• class Honda4 extends Bike{
• void run(){System.out.println("running safely");}
• public static void main(String args[]){
• Bike obj = new Honda4();
• obj.run();
• }
• }
• An event in Java is an object that is created when something changes within a graphical user
interface. If a user clicks on a button, clicks on a combo box, or types characters into a text
field, etc., then an event triggers, creating the relevant event object. This behavior is part of
Java's Event Handling mechanism and is included in the Swing GUI library.
• How Events Work
• Event handling in Java is comprised of two key elements:
• The event source, which is an object that is created when an event occurs. Java provides
several types of these event sources, discussed in the section Types of Events below.
• The event listener, the object that "listens" for events and processes them when they occur.
• public void actionPerformed(ActionEvent e){
• tf.setText("Welcome");
• }
• ArrayList class extends AbstractList class and implements the List interface.
• ArrayList supports dynamic array that can grow as needed. ArrayList has three
constructors.
• ArrayList() //It creates an empty ArrayList
• ArrayList( Collection C ) //It creates an ArrayList that is initialized with elements of
the Collection C
• ArrayList( int capacity ) //It creates an ArrayList that has the specified initial capacity
• LinkedList class
• LinkedList class extends AbstractSequentialList and
implements List,Deque and Queue inteface.
• LinkedList has two constructors.
• LinkedList() //It creates an empty LinkedList
• LinkedList( Collection C ) //It creates a Lin
• final(lowercase) is a reserved keyword in java. We can’t use it as an identifier
as it is reserved. We can use this keyword with variables, methods and also
with classes. The final keyword in java has different meaning depending upon
it is applied to variable, class or method.
• final int b = 6;
• finally is also a reserved keyword in java i.e, we can’t use it as an identifier.
The finally keyword is used in association with a try/catch block and
guarantees that a section of code will be executed, even if an exception is
thrown. The finally block will be executed after the try and catch blocks, but
before control transfers back to its origin.
• final int b = 6;
• try {
• System.out.println("inside B");
• return;
• }
• finally
• {
• System.out.println("B's finally");
• }
• }
• finalize() method is a protected and non-static method of java.lang.Object
class. This method will be available in all objects you create in java. This
method is used to perform some final operations or clean up operations on
an object before it is removed from the memory.
4 method of file class
• boolean canExecute() : Tests whether the application can execute the file denoted by this
abstract pathname.
• boolean canRead() : Tests whether the application can read the file denoted by this abstract
pathname.
• boolean canWrite() : Tests whether the application can modify the file denoted by this abstract
pathname.
• int compareTo(File pathname) : Compares two abstract pathnames lexicographically.
• boolean createNewFile() : Atomically creates a new, empty file named by this abstract
pathname .
• static File createTempFile(String prefix, String suffix) : Creates an empty file in the default
temporary-file directory.
• boolean delete() : Deletes the file or directory denoted by this abstract pathname.
• boolean equals(Object obj) : Tests this abstract pathname for equality with the given object.
• There are two basic types of dialogs: modal and modeless. Modal dialogs block
input to other top-level windows. Modeless dialogs allow input to other windows.
An open file dialog is a good example of a modal dialog....
Message dialogs
• ERROR_MESSAGE.
• WARNING_MESSAGE.
• QUESTION_MESSAGE.
• INFORMATION_MESSAGE.
• option dialog
• The input dialog has an additional component for user input. This can be a text field
into which the user can type an arbitrary string, or a combo box from which the user
can select one item.
• he PLAIN_MESSAGE type has no icon. Each dialog type also has a method that lets
you supply your own icon instead. For each dialog type, you can specify a message.
This message can be a string, an icon, a user interface component, or any other
object. Here is how the message object is displayed:
• The showConfirmDialog and showOptionDialog return integers to indicate which button the user
chose. For the option dialog, this is simply the index of the chosen option or the value
CLOSED_OPTION if the user closed the dialog instead of choosing an option. For the confirmation
dialog, the return value can be one of the following:
• Difference Between Interface and Abstract Class
• Main difference is methods of a Java interface are implicitly abstract and cannot have
implementations. A Java abstract class can have instance methods that implements a default
behavior.
• Variables declared in a Java interface is by default final. An abstract class may contain non-
final variables.
• Members of a Java interface are public by default. A Java abstract class can have the usual flavors of
class members like private, protected, etc..
• Java interface should be implemented using keyword “implements”; A Java abstract class should be
extended using keyword “extends”.
• An interface can extend another Java interface only, an abstract class can extend another Java class
and implement multiple Java interfaces.
• A Java class can implement multiple interfaces but it can extend only one abstract class.
• Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be
instantiated, but can be invoked if a main() exists.
• Explain Java’s delegation event model
• The event model is based on the Event Source and Event Listeners. Event Listener
is an object that receives the messages / events. The Event Source is any object
which creates the message / event. The Event Delegation model is based on –
The Event Classes, The Event Listeners, Event Objects.
An event occurs (like mouse click, key press, etc) which is followed by the event is
broadcasted by the event source by invoking an agreed method on all event
listeners. The event object is passed as argument to the agreed-upon method.
Later the event listeners respond as they fit, like submit a form, displaying a
message / alert etc.
• throw throws
• 1) Java throw keyword is used to explicitly throw an exception.
• Java throws keyword is used to declare an exception.
• 2) Checked exception cannot be propagated using throw only.
• Checked exception can be propagated with throws.
• 3) Throw is followed by an instance.
• Throws is followed by class.
• 4) Throw is used within the method.
• Throws is used with the method signature.
• 5) You cannot throw multiple exceptions.
• You can declare multiple exceptions e.g.
• public void method()throws IOException,SQLException