Java Important
Java Important
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.
Static variable: If you declare any variable as static, it is known as a static variable.
o The static variable gets memory only once in the class area at the time of class
loading.
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Output:
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.
Example:
class Student{
int rollno;
String name;
static String college = "ITS";
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
import java.io.*;
import java.util.Scanner;
class lab5geo
float areasq,arearect,areacir;
areasq=side*side;
arearect=length*breadth;
areacir=3.14f*radius*radius;
float L = input.nextFloat();
float B = input.nextFloat();
obj.area(L,B);
obj.area(rad);
} //end public
}//end class
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example:
class Vehicle{
//defining a method
void run()
System.out.println("Vehicle is running");}
void run()
obj.run();//calling method
Output:
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 extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
Single Inheritance
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing...");}
class TestInheritance3{
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
Example:
import java.io.*;
class lab3
{
public static void main(String arg[])
{
String s1 = "COMPUTER SCIENCE";
String s2 = "COMPUTER SCIENCE";
System.out.println("First String is:" +s1);
System.out.println("Second String is:" +s2);
System.out.println("String converted into lowercase:" +s1.toLowerCase());
System.out.println("String converted into uppercase:"+s2.toUpperCase());
System.out.println("Substring is:"+s1.substring(4,5));
System.out.println("String length:"+s1.length());
System.out.println("comparison of 2 strings:"+s1.equals(s2));
System.out.println("the first occurance of 'e' is:" + s1.indexOf('E'));
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() meth
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
The graphics class defines a number of drawing functions, Each shape can be drawn edge-
only or filled. To draw shapes on the screen, we may call one of the methods available in the
graphics class.
Syntax
void drawLine(int startX, int startY, int endX, int endY)
drawLine() displays a line in the current drawing color that begins at (start X, start Y) and
ends at (endX, end Y).
Example: g.drawLine(0,0,100,100);
Rectangle
The drawRect() and fillRect() methods display an outlined and filled rectangle, respectively.
Syntax
The upper-left corner of the rectangle is at(top,left). The dimensions of the rectangle are
specified by width and height.
Syntax
void drawRoundRect(int top, int left, int width, int height int Xdiam, int YDiam)
void fillRoundRect(int top, int left, int width, int height int Xdiam, int YDiam)
The Graphics class does not contain any method for circles or ellipses. To draw an ellipse,
use drawOval(). To fill an ellipse, use fillOval().
Syntax
Drawing Arcs
An arc is a part of oval. Arcs can be drawn with draw Arc() and fillArc() methods.
Syntax
void drawArc(int top, int left, int width, int height, int startAngle, int sweetAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweetAngle)
User Defined Exception or custom exception is creating your own exception class and throws
that exception using ‘throw’ keyword. This can be done by extending the class Exception.
class JavaException{
try{
catch(MyException e){
System.out.println(e) ;
int a;
MyException(int b) {
a=b;
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
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.
There are mainly three reasons to use interface. They are given below.
Syntax:
interface <interface_name>{
// by default.
Example:
interface printable{
void print();
obj.print();
Output:
Hello
Create a thread by a new class that extends Thread class and create an instance of that class.
The extending class must override run() method which is the entry point of new thread.
Example
mt.start();
Output :
Thread started running..
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the
application.
An exception normally disrupts the normal flow of the application that is why we use
exception handling.
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.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.
13. Explain Final method, final class and final variables in java OR
Using the final keyword means that the value can’t be modified in the future.
Final variables:
If a variable is declared with the final keyword, its value cannot be changed once initialized.
Note that the variable does not necessarily have to be initialized at the time of declaration.
Final methods:
A method, declared with the final keyword, cannot be overridden or hidden by subclasses.
Example:
Final classes:
Example:
//...
class Subclass extends FinalClass{ //attempting to subclass a final class throws an error
//...
• In java, 3 streams are created for us automatically. All these streams are attached with
console.
import java.io.FileInputStream;
import java.io.InputStream;
try {
input.read(array);
System.out.println(data);
input.close();
catch (Exception e) {
e.getStackTrace();
class lab5overload
class overload
overload(float r)
float ar;
ar=3.14f * r * r;
int ar=a*b;
overload (int a)
int ar=a*a;
} //end class
17. Explain package with the steps to create a user defined package with an example.
Packages can have collection of classes, interfaces and sub packages. Each sub packages can
in turn have classes and interfaces.
•Packages are used to reuse the classes written in one program into another program without
physically copying them into the program under development.
19. Explain Data Input Stream and Data Output Stream in Java.
Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.
Syntax:
Methods:
Example:
package com.javatpoint;
import java.io.*;
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be
read by a data input stream.
Syntax:
Methods:
Example:
package com.javatpoint;
import java.io.*;
inst.read(ary);
System.out.print(k+"-");
The wrapper class in Java provides the mechanism to convert primitive into object
and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and
objects into primitives automatically. The automatic conversion of primitive into an
object is known as autoboxing and vice-versa unboxing.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Example:
class wrapperdemo
byte a = 1;
int b = 10;
float c = 18.6f;
double d = 250.5;
char e='a';
Character charobj=e;
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
b) Abstract class
Abstract class:
Abstract Method:
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example:
obj.run();
Output:
running safely
import java.awt.*;
import java.applet.*;
String n;
String a;
n = getParameter("name");
a = getParameter("age");
/*
</applet>
*/
container component
2. ex: JPanel,JWindow