JAVA Material
JAVA Material
JAVA Material
Declaring a class as final implicitly declares all of its methods as final, too. It is illegal
to declare a class as both abstract and final since an abstract class is incomplete by
itself and relies upon its subclasses to provide complete implementations
Method Overloading and Overriding
Example: Example:
class demo class demo
{ {
void add(){ void add(){
System.out.println(“Sum=”+(10+20)); } System.out.println(“Sum=”+(10+20));
}
void add(int a, int b) { }
System.out.println(“Sum=”+(a+b)); } class demo1 extends demo
int add(){ {
return a+b; void add(){
} System.out.println(“Sum=”+(80+40));
} }
class example }
{ class example
public static void main(String args[]){ {
demo d = new demo(); public static void main(String args[]){
d.add(); demo1 d = new demo1();
d.add(10,20); d.add();
int a = add(); super.add();
} }
} }
interface NewInterface {
// static method
static void hello()
{
System.out.println("Hello, New Static Method Here");
}
// Implementation Class
public class InterfaceDemo implements NewInterface {
@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}
Defining Package:
A set of classes and interfaces grouped together are known as Packages in JAVA. To
create a package is quite easy: simply include a package command as the first statement in a
Java source file.
Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes
are stored.
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
The general form of a multileveled package statement is :
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system.
For example, a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment.
Importing Package
Import keyword is used to import the package. the general form of the import
statement: import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.)
Example:
import java.util.Date;
import java.io.*;
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show() }
}
Access Specifiers
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
1. private access modifier: The private access modifier is accessible only within class. 2.
default access modifier: If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package.
3. protected access modifier: The protected access modifier is accessible within package and
outside the package but through inheritance only. The protected access modifier can be
applied on the data member, method and constructor. It can't be applied on the class.
4. public access modifier: The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
Exception:
An Exception, It can be defined as an abnormal event that occurs during program execution
and disrupts the normal flow of instructions.
An exception is a run-time error that occurs during the execution of a java program.
Example: If you divide a number by zero or open a file that does not exist, an
exception is raised.
1. try Block: The java code that you think may produce an exception is placed within a try
block for a suitable catch block to handle the error.
2. catch Block: Exceptions thrown during execution of the try block can be caught and
handled in a catch block.
3. throw keyword is used to throw an exception explicitly. Only object of
Throwable class or its sub classes can be thrown.
4. finally Block: A finally block is always executed, regardless of the cause of exit from the
try block, or whether any catch block was executed.
5. throws: Any method capable of causing exceptions must list all the exceptions possible
during its execution, so that anyone calling that method gets a prior knowledge about which
exceptions to handle. A method can do so by using the throws keyword.
Example:
import java.util.Scanner;
public class Custom_Exception
{
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two numbers: ");
int a = scanner.nextInt();
int b = scanner.nextInt();
try {
if (b == 0) {
throw new ArithmeticException("Division by zero is not
allowed!");
}
float result = a / b;
System.out.println("Result: " + result);
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
finally {
scanner.close();
}
}
}
Inbuilt Exceptions in JAVA
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
class ThreadDemo {
public static void main(String args[]) {
NewThread n = new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Here main thread is created first and then main thread calls constructor of NewThread class.
In NewThread class Demo thread is created by calling constructor of Thread class. Then start
function is called. Which in turn invokes the run function defined in runnable interface.
Creating Thread by extending Thread class
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Here main thread is created first and then main thread calls constructor of NewThread class.
In NewThread class Demo thread is created by calling super class constructor. Then start
function is called. Which in turn invokes the run function defined in Thread class.
Enumeration
Enumeration is a list of named constants.
Enumeration is created using enum keyword
Example:
// An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
Once you have defined an enumeration, you can create a variable of that type. However,
even though enumerations define a class type, you do not instantiate an enum using new.
Instead, you declare and use an enumeration variable in much the same way as you do one
of the primitive types. For example, this declares ap as a variable of enumeration type
Apple:
Apple ap;
Because ap is of type Apple, the only values that it can be assigned (or can contain) are
those defined by the enumeration. For example, this assigns ap the value RedDel:
ap = Apple.RedDel;
The values( ) method returns an array that contains a list of the enumeration constants.
The valueOf( ) method returns the enumeration constant whose value corresponds to the
string passed in str. In both cases, enum-type is the type of the enumeration
Example:
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo2 {
public static void main(String args[])
{
Apple ap;
System.out.println("Here are all Apple constants:");
// use values()
Apple allapples[] =
Apple.values(); for(Apple a :
allapples)
System.out.println(a);
System.out.println();
// use valueOf()
ap = Apple.valueOf("Winesap");
System.out.println("ap contains " +
ap); }