java2nd
java2nd
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the
accessibility of classes, methods, and other members.
Default (No keyword required): When we do not mention any access modifier, it is called
default access modifier. The default modifier is accessible only within package.
Private: Private Data members and methods are only accessible within the class. Class and
Interface cannot be declared as private. If a class has private constructor then you cannot
create the object of that class from outside of the class.
Protected: Protected data member and method are only accessible by the classes of the same
package and the subclasses present in any package.
Public: The members, methods and classes that are declared public can be accessed from
anywhere. Public are also called universal access modifiers.
Packages in Java
Packages in Java are groups of similar types of classes, interface and sub packages.
Syntax:-
package;
Reusability: The classes contained in the packages of another program can be easily reused.
Better Organization: Java package is used to categorize the classes and interfaces so that
they can be easily maintained.
Protection: Java package provides access protection.
Name Conflicts: Java package removes naming collision.
Types of Packages
Built-in Package: Existing Java package for example java.lang, java.util etc.
User-defined-package: Java package created by user to categorize their project's classes and
interface.
//save as FirstProgram.java
package learnjava;
System.out.println("Welcome to package");
import keyword is used to import built-in and user-defined packages into your java source file
so that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to any class that is present in a different package:
If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, there is no need to use
the import statement.
Example :
//save by A.java
package pack;
public class A {
System.out.println("Hello");
//save by B.java
package mypack;
class B {
obj.msg();
Output: Hello
2. Using packagename.classname
Example :
//save by A.java
package pack;
public class A {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B {
obj.msg();
Output: Hello
3. Using packagename.*
To import all the classes from a particular package but the classes and interface inside the
subpackages will not be available for use.
Example :
//save by First.java
package learnjava;
System.out.println("Hello");
//save by Second.java
package Java;
import learnjava.*;
class Second {
obj.msg();
Output: Hello
Subpackage
A package created inside another package is known as a subpackage. When we import a
package, subpackages are not imported by default. They have to be imported explicitly. In the
following statement :
import java.util.*;
Example of Subpackage
package com.javatpoint.core;
class Simple{
System.out.println("Hello subpackage");
A class that is declared with abstract keyword, is known as abstract class in java.
It can have abstract and non-abstract methods.
It cannot be instantiated. Abstract classes can have Constructors, Member variables and
Normal methods.
When you extend Abstract class with abstract method, you must define the abstract
method in the child class, or make the child class abstract.
Syntax :
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Syntax :
abstract class A
class B extends A
void callme()
System.out.println("this is callme.");
B b = new B();
b.callme();
Interface in Java
Syntax :
interface interface_name { }
Declaring Interfaces
Example of Interface
interface Person
datatype variablename=value;
Implementing Interfaces
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
Example:
interface Person
System.out.println("Run fast");
obj.run();
Example
interface NewsPaper
news();
colorful();
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
Example:
interface Developer
void disp();
interface Manager
void show();
{
public void disp()
obj.disp();
obj.show();
Final is a keyword in Java that is used to restrict the user and can be used in many respects. It is
a non-access modifier. The final keyword can be used in following way:
1.) Final at variable level: When a variable is declared with final keyword, it’s value can’t be
modified, essentially, a constant.
Example:
class FinalVariable
{
public static void main(String[] args)
{
final int hours=24;
System.out.println("Hours in 6 days = " + hours * 6);
}
}
Output: Hours in 6 days = 144
2.) Final at method level: When a method is declared with final keyword, method cannot be
overridden.
Example:
class X
{
final void getMethod()
{
System.out.println(“X method has been called”);
}
}
class Y extends X
{
void getMethod() //cannot override
{
System.out.println(“Y method has been called”);
}
}
class FinalMethod
{
public static void main(String[] args)
{
Y obj = new Y();
obj.getMethod();
}
}
3.) Final at class level: When a class is declared with final keyword, class cannot be extended
(inherited).
Example:
final class X
{
class Y extends X
class FinalClass
Super keyword in java is a reference variable that is used to refer parent class object.
1) To access the data members of parent class when both parent and child class have member
with same name
3) To access the method of parent class when child class has overridden that method.
1. Use of super with variables: When you have a variable in child class which is already present
in the parent class then in order to access the variable of parent class, you need to use the
super keyword.
Example:
class Employee
{
float salary=10000;
float salary=20000;
void display()
class Supervarible
HR obj=new HR();
obj.display();
2. Use of super with methods: The super keyword can also be used to invoke parent class
method. It should be used if subclass contains the same method as parent class. In other words,
it is used if method is overridden.
Example:
class Student
{
void message()
void message()
void display()
s.display();
Example:
class Employee
Employee()
HR()
class Supercons
HR obj=new HR();
}
}
HR class Constructor
import java.io.Serializable;
int id;
String name;
this.id = id;
this.name = name;
this.age=age;
The static keyword is used in java mainly for memory management. static is a non-access
modifier in Java which is applicable for the blocks, variables, methods, nested classes.
1) static variables: When a variable is declared as static, then a single copy of variable is
created and shared among all objects at class level. Static variables are, essentially,
global variables. All instances of the class share the same static variable.
2) static method: When a method is declared with static keyword, it is known as static
method. The most common example of a static method is main( ) method. Any static
member can be accessed before any objects of its class are created, and without
reference to any object. Methods declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
.......
.......
3) static block: static block is used for initializing the static variables. This block gets
executed when the class is loaded in the memory. A class can have multiple Static
blocks, which will execute in the same sequence in which they have been written into
the program.
class A{
System.out.println("Hello main");
Hello main
Volatile Keyword in Java
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache
value of this variable and always read it from main memory.
Java volatile keyword cannot be used with method or class and it can only be used with
variable.
If the variable keeps on changing such type of variables we have to declare with volatile
modifier.
If a variable declared as volatile then for every thread a separate local copy will be created.
Example:
return value;
this.value = value;
Synchronization in java is the capability to control the access of multiple threads to any shared
resource. If a method or block declared as a Synchronized then at a time only one thread is
allowed to operate on the given object. The synchronization is mainly used to
synchronized (expression) {
Examples:
class BankAccount {
this.balance -= amount;
this.balance += amount;
The following code example shows a synchronized statement is applied for a code block, not a
method:
synchronized (lock) {
System.out.println("Synchronized statement");
}
String Handling in Java
The basic aim of String Handling concept is storing the string data in the main memory (RAM),
manipulating the data of the String, retrieving the part of the String etc. String Handling
provides a lot of concepts that can be performed on a string such as concatenation of string,
comparison of string, find sub string etc.
String: String is a sequence of characters enclosed within double quotes (" ") is known as String.
2. By new keyword: In such case, JVM will create a new string object.
In java programming to store the character data we have a fundamental datatype called char.
Similarly to store the string data and to perform various operations on String data, we have
three predefined classes they are:
1. String class: It is a predefined class in java.lang package can be used to handle the String.
String class is immutable that means whose content can not be changed at the time of
execution of program.String class object is immutable that means when we create an object
of String class it never changes in the existing object.
Example:
class StringHandling
{
public static void main(String arg[])
{
String s=new String("java");
s.concat("software");
System.out.println(s);
}
}
Output: java
Methods of String class
length(): This method is used to get the number of character of any string.
charAt(): This method is used to get the character at a given index value.
toUpperCase(): This method is use to convert lower case string into upper case.
toLowerCase(): This method is used to convert lower case string into upper case.
concat(): This method is used to combined two string.
equals(): This method is used to compare two strings, It return true if strings are same
otherwise return false. It is case sensitive method.
equalsIgnoreCase(): This method is case insensitive method, It return true if the contents of
both strings are same otherwise false.
compareTo(): This method is used to compare two strings by taking unicode values, It
return 0 if the string are same otherwise return +ve or -ve integer values.
compareToIgnoreCase(): This method is case insensitive method, which is used to compare
two strings similar to compareTo().
startsWith(): This method return true if string is start with given another string, otherwise it
returns false.
endsWith(): This method return true if string is end with given another string, otherwise it
returns false.
subString(): This method is used to get the part of given string.
indexOf(): This method is used find the index value of given string. It always gives starting
index value of first occurrence of string.
lastIndexOf(): This method used to return the starting index value of last occurence of the
given string.
trim(): This method remove space which are available before starting of string and after
ending of string.
split(): This method is used to divide the given string into number of parts based on
delimiter (special symbols like @ space , ).
replace(): This method is used to return a duplicate string by replacing old character with
new character.
2. StringBuffer: It is a predefined class in java.lang package can be used to handle the String,
whose object is mutable that means content can be modify. StringBuffer class is working
with thread safe mechanism that means multiple thread are not allowed simultaneously to
perform operation of StringBuffer. StringBuffer class object is mutable that means when we
create an object of StringBuilder class it can be change.
Example:
class StringHandling
sb.append("software");
System.out.println(sb);
Output: javasoftware
reverse(): This method is used to reverse the given string and also the new value is replaced
by the old string.
insert(): This method is used to insert either string or character or integer or real constant
or boolean value at a specific index value of given string.
append(): This method is used to add the new string at the end of original string.
replace(): This method is used to replace any old string with new string based on index
value.
deleteCharAt(): This method is used to delete a character at given index value.
delete(): This method is used to delete string form given string based on index value.
toString(): This method is used to convert mutable string value into immutable string.
3. StringBuilder: It is a predefined class in java.lang package can be used to handle the String.
StringBuilder class is almost similar to to StringBuffer class. It is also a mutable object. The
main difference StringBuffer and StringBuilder class is StringBuffer is thread safe that means
only one threads allowed at a time to work on the String where as StringBuilder is not
thread safe that means multiple threads can work on same String value.
Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally.
Error VS Exception
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception: The exception that can be predicted by the programmer at the compile
time. Example: File that need to be opened is not found. These types of exceptions must be
checked at compile time.
2. Unchecked Exception: Unchecked exceptions are the class that extends RuntimeException.
Unchecked exceptions are ignored at compile time. Example: ArithmeticException,
NullPointerException, Array Index out of Bound exception. Unchecked exceptions are
checked at runtime.
3. Error: Errors are typically ignored in code because you can rarely do anything about an
error. Example: if stack overflow occurs, an error will arise. This type of error cannot be
handled in the code.
Exception Handling Mechanism
1. try: The try block contains set of statements where an exception can occur. try block must
be followed by either catch or finally block.
Syntax:
try{
//statements that may cause an exception
}
2. catch: 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.
Syntax:
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
3. finally: A finally block must be associated with a try block, you cannot use finally without a
try block. You should place those statements in this block that must be executed always.
Syntax:
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
4. throw: throw keyword is used to throw an exception explicitly. Only object of Throwable
class or its sub classes can be thrown.
Syntax :
throw ThrowableInstance
5. Throws: Throws clause is used to declare an exception, which means it works similar to the
try-catch block.
Syntax :
type method_name(parameter_list) throws exception_list
{
//definition of method
}
class Example
try{
int num=121/0;
System.out.println(num);
catch(ArithmeticException e){
*/
finally{
System.out.println("Out of try-catch-finally");
}
}
Out of try-catch-finally
class Test
try
check();
catch(ArithmeticException e)
System.out.println("caught" + e);
}
Output: Inside check function
caughtjava.lang.ArithmeticException: demo
Multithreading in Java
The process of executing multiple threads simultaneously is known as multithreading.
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread.
Thread in Java
New: A thread begins its life cycle in the new state. It remains in this state until the start()
method is called on it.
Runnable: After invocation of start() method on new thread, the thread becomes runnable.
Running: A thread is in running state if the thread scheduler has selected it.
Waiting: A thread is in waiting state if it waits for another thread to perform a task. In this stage
the thread is still alive.
Terminated: A thread enters the terminated state when it complete its task.
Types of Thread
User thread: This is created by the Java programmer or user. JVM wait for these threads to
finish their task. These threads are foreground threads.
Daemon thread: This is created by the operating system. JVM doesn’t wait for daemon threads
to finish their task. These threads are used to perform some background tasks like garbage
collection.
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).
Thread class is the main class on which Java's Multithreading system is based. Thread class,
along with its companion interface Runnable will be used to create and run threads for utilizing
Multithreading feature of Java.
Thread ( )
Thread ( Runnable r )
Thread class also defines many methods for managing threads. Some of them are,
Method Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
isAlive() checks if thread is still running or not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified time
1) By extending Thread class: This approach provides more flexibility in handling multiple
threads created using available methods in Thread class.
Example:
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...
2) By implementing Runnable interface: If your class is intended to be executed as a thread
then you can achieve this by implementing a Runnable interface.
Example:
System.out.println("thread is running...");
t1.start();
wait()-It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
notify()-It wakes up one single thread that called wait() on the same object.
notifyAll()-It wakes up all the threads that called wait() on the same object.
Thread Deadlock
Deadlock is a situation of complete Lock, when no thread can complete its execution because
lack of resources. Deadlock describes a situation where two or more threads are blocked
forever, waiting for each other. Deadlock occurs when multiple threads need the same locks
but obtain them in different order.
Example of deadlock
class Pen{}
class Paper{}
synchronized(pn)
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pr)
};
synchronized(pr)
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pn)
};
t1.start();
t2.start();