You are on page 1of 15

CLASS:

A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type.

OBJECT:

It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of :

State : It is represented by attributes of an object. It also reflects the properties of an object.

Behavior : It is represented by methods of an object. It also reflects the response of an object with other
objects.

Identity : It gives a unique name to an object and enables one object to interact with other objects.

Strings in Java:

Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot
grow), Strings are immutable as well.

EXAMPLE OF STRING:

// Java code to illustrate String

import java.io.*;

import java.lang.*;

class Test {

public static void main(String[] args)

{
// Declare String without using new operator

String s = "GeeksforGeeks";

// Prints the String.

System.out.println("String s = " + s);

// Declare String using new operator

String s1 = new String("GeeksforGeeks");

// Prints the String.

System.out.println("String s1 = " + s1);

Collections in Java

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.

The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root”
interfaces of Java collection classes.

EXAMPLE:
// Java program to show why collection framework was needed

import java.io.*;

import java.util.*;

class Test

public static void main (String[] args)

// Creating instances of array, vector and hashtable

int arr[] = new int[] {1, 2, 3, 4};

Vector<Integer> v = new Vector();

Hashtable<Integer, String> h = new Hashtable();

v.addElement(1);

v.addElement(2);

h.put(1,"geeks");

h.put(2,"4geeks");

// Array instance creation requires [], while Vector

// and hastable require ()

// Vector element insertion requires addElement(), but

// hashtable element insertion requires put()

// Accessing first element of array, vector and hashtable

System.out.println(arr[0]);

System.out.println(v.elementAt(0));

System.out.println(h.get(1));
// Array elements are accessed using [], vector elements

// using elementAt() and hashtable elements using get()

Packages In Java:

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages
are used for:

Preventing naming conflicts. For example there can be two classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee

Making searching/locating and usage of classes, interfaces, enumerations and annotations easier

EXAMPLE:

// Java program to demonstrate accessing of members when

// corresponding classes are imported and not imported.

import java.util.Vector;

public class ImportDemo

public ImportDemo()

// java.util.Vector is imported, hence we are

// able to access directly in our code.

Vector newVector = new Vector();


// java.util.ArrayList is not imported, hence

// we were referring to it using the complete

// package.

java.util.ArrayList newList = new java.util.ArrayList();

public static void main(String arg[])

new ImportDemo();

Exceptions in Java

What is an Exception?

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at
run time, that disrupts the normal flow of the program’s instructions.

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.
// Java program to demonstrate how exception is thrown.

class ThrowsExecp{

public static void main(String args[]){

String str = null;

System.out.println(str.length());

}
Let us see an example that illustrate how run-time system searches appropriate exception handling code
on the call stack :

// Java program to demonstrate exception is thrown

// how the runTime system searches th call stack

// to find appropriate exception handler.

class ExceptionThrown

// It throws the Exception(ArithmeticException).

// Appropriate Exception handler is not found within this method.

static int divideByZero(int a, int b){

// this statement will cause ArithmeticException(/ by zero)

int i = a/b;

return i;

// The runTime System searches the appropriate Exception handler

// in this method also but couldn't have found. So looking forward

// on the call stack.

static int computeDivision(int a, int b) {

int res =0;

try

res = divideByZero(a,b);

}
// doesn't matches with ArithmeticException

catch(NumberFormatException ex)

System.out.println("NumberFormatException is occured");

return res;

// In this method found appropriate Exception handler.

// i.e. matching catch block.

public static void main(String args[]){

int a = 1;

int b = 0;

try

int i = computeDivision(a,b);

// matching ArithmeticException

catch(ArithmeticException ex)

// getMessage will print description of exception(here / by zero)

System.out.println(ex.getMessage());

}
}

Methods in Java

A method is a collection of statements that perform some specific task and return the result to the caller.
A method can perform some specific task without returning anything. Methods allow us to reuse the
code without retyping the code. In Java, every method must be part of some class which is different from
languages like C, C++, and Python.

Methods are time savers and help us to reuse the code without retyping the code

Modifier-: Defines access type of the method i.e. from where it can be accessed in your application. In
Java, there 4 type of the access specifiers.

public: accessible in all class in your application.

protected: accessible within the class in which it is defined and in its subclass(es)

private: accessible only within the class in which it is defined.

default (declared/defined without using any modifier) : accessible within same class and package within
which its class is defined.

The return type : The data type of the value returned by the method or void if does not return a value.

Method Name : the rules for field names apply to method names as well, but the convention is a little
different.

Parameter list : Comma separated list of the input parameters are defined, preceded with their data
type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().

Exception list : The exceptions you expect by the method can throw, you can specify these exception(s).

Method body : it is enclosed between braces. The code you need to be executed to perform your
intended operations.
// Program to illustrate methodsin java

import java.io.*;

class Addition {

int sum = 0;

public int addTwoInt(int a, int b){

// adding two integer value.

sum = a + b;

//returning summation of two values.

return sum;

}
class GFG {

public static void main (String[] args) {

// creating an instance of Addition class

Addition add = new Addition();

// calling addTwoInt() method to add two integer using instance created

// in above step.

int s = add.addTwoInt(1,2);

System.out.println("Sum of two integer values :"+ s);

What is Applet?

An applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted
on a web server.

Applets are used to make the web site more dynamic and entertaining.

Important points :

All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.

Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool called applet viewer.

In general, execution of an applet does not begin at main() method.

Output of an applet window is not performed by System.out.println(). Rather it is handled with various
AWT methods, such as drawString().

Life cycle of an applet :

It is important to understand the order in which the various methods shown in the above image are
called. When an applet begins, the following methods are called, in this sequence:

init( )

start( )

paint( )

When an applet is terminated, the following sequence of method calls takes place:
stop( )

destroy( )

Let’s look more closely at these methods.

init( ) : The init( ) method is the first method to be called. This is where you should initialize variables.
This method is called only once during the run time of your applet.

start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped. Note that init( ) is called once i.e. when the first time an applet is loaded whereas start( ) is
called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and
comes back, the applet resumes execution at start( ).

paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is running may be
overwritten by another window and then uncovered. Or the applet window may be minimized and then
restored.

paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must
redraw its output, paint( ) is called.

The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context is used
whenever output to the applet is required.

Note: This is the only method among all the method mention above, which is parametrised. It’s
prototype is

public void paint(Graphics g)

where g is an object reference of class Graphic.

Now the Question Arises:

Q. In the prototype of paint() method, we have created an object reference without creating its object.
But how is it possible to create object reference without creating its object?

Ans. Whenever we pass object reference in arguments then the object will be provided by its caller itself.
In this case the caller of paint() method is browser, so it will provide an object. The same thing happens
when we create a very basic program in normal Java programs. For Example:
public static void main(String []args){}

Here we have created an object reference without creating its object but it still runs because it’s caller,i.e
JVM will provide it with an object.

stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page, for example. When stop( ) is called, the applet is probably
running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible.
You can restart them when start( ) is called if the user returns to the page.

destroy( ) : The destroy( ) method is called when the environment determines that your applet needs to
be removed completely from memory. At this point, you should free up any resources the applet may be
using. The stop( ) method is always called before destroy( ).

// A Hello World Applet

// Save file as HelloWorld.java

import java.applet.Applet;

import java.awt.Graphics;

// HelloWorld class extends Applet

public class HelloWorld extends Applet

// Overriding paint() method

@Override

public void paint(Graphics g)

g.drawString("Hello World", 20, 20);

You might also like