Java Module 2
Java Module 2
MODULE 2
Java module 2
1. What is the importance of java API?
In simple terms, API, or Application Programming Interface, is a connection that allows
you to make software.APIs are important software components bundled with the JDK.
APIs in Java include classes, interfaces, and user Interfaces. They enable developers to
integrate various applications and websites and offer real-time information.
2. What is a byte code?
Byte codeis program code that has been compiled from source code into low-level code
designed for a software interpreter. Byte code is the compiled format for Java programs.
Once a Java program has been converted to byte code, it can be transferred across a
network and executed by Java Virtual Machine (JVM). Byte code files generally have a
.class extension.
3. How JVM works? Explain JVM Architecture?
OR
4. What is JVM?
Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the
Java Code or applications. It converts Java bytecode into machines language. JVM is a
part of Java Run Environment (JRE). In other programming languages, the compiler
produces machine code for a particular system. However, Java compiler produces code
for a Virtual Machine known as Java Virtual Machine.
How JVM works:First, Java code is compiled into byte code. This byte code gets
interpreted on different machines
Between host system and Java source, Byte code is an intermediary language.
JVM in Java is responsible for allocating memory space.
Java applications are called WORA (Write Once Run Anywhere). This means a
programmer can develop Java code on one system and can expect it to run on any other
Java-enabled system without any adjustment. This is all possible because of JVM.
When we compile a .java file, .class files (contains byte-code) with the same class names
present in .java file are generated by the Java compiler. This .class file goes into various
steps when we run it. These steps together describe the whole JVM.
JVM Architecture
Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and var-name is the name of array variable that is linked to the
array. That is, to use new to allocate an array, you must specify the type and number of
elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
Array Literal
In a situation, where the size of the array and variables of array are already known, array
literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java
*
Multiplicatio Multiplies values on either side of the operator A*B=200
n
Relational Operators: These operators compare the values on either side of them and decide
the relation among them. Assume A = 10 and B = 20.
Logical Operators: The following are the Logical operators present in Java:
~
returns the one’s complement. (all bits reversed) ~a
(Complement)
System.out.println(a|b); //63=111111
System.out.println(a^b); //55=11011
System.out.println(~a); //-59
Unary Operator :Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.
Ternary Operators in Java: The ternary operator is a conditional operator that decreases the
length of code while performing comparisons and conditionals. This method is an alternative
for using if-else and nested if-else statements. The order of execution for this operator is from
left to right.
Syntax:
Shift Operators in Java: Shift operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number. There are three different types of shift operators,
namely left shift operator()<<, signed right operator(>>) and unsigned right shift
operator(>>>).
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
if(Boolean_expression) {
// Executes when the Boolean expression is true
}
else {
// Executes when the Boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
public class Test {
public static void main(String args[]) {
int x = 30;
if( x< 20 ) {
System.out.print("This is if statement");
}
else {
System.out.print("This is else statement");
}
}
}
While loop starts with the checking of condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason it is also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for the
next iteration.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
Example
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;
while (x <= 4)
{
System.out.println("Value of x:" + x);
do while loop starts with the execution of the statement(s). There is no checking of any
condition for the first time.
After the execution of the statements, and update of the variable value, the condition is
checked for true or false value. If it is evaluated to true, next iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
It is important to note that the do-while loop will execute its statements at least once
before any condition is checked, and therefore is an example of exit control.
Example
class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}
Example
class ForLoopDemo
{
public static void main(String args[])
{
for(int num = 1; num <= 5; num++)
{
System.out.println(num);
}}}
24.Explain how data and methods are organized in an object oriented program
with suitable illustration.
OOP languages involve using a series of classes to keep data and functions organized.
Every class will contain variables and functions specific to that class that are called from
elsewhere in the program where that class is used.
First an object has some properties and that properties represent the data
Example:- Student object has some properties like name,age,roll_noetc so that is data
about the object.Let as see program
class Student
{
String name;
int age;
int roll_no;
}
Now second come methods(functions),the methods are the operations which are
performed on the data of the object.
Example:- student class has some function like getdetail,display etc.
class Student
{
String name;
int age;
void getdetail(){
name=”java”;
age=20;
}
void display(){ System.out.println(“Name=”+name+”Age=”+age);}
}
25.What are the two sections in class definition?
A class is a user defined data type which contains the set of similar data and the functions
that the objects posses.A class serves as a blueprint or template for its objects.
Once a class has been defined, any number of objects belonging to that class can be
created.The objects of a class are also known as instances or the variables of that class.
Syntax for defining a class as follows:
class class_name
{
//variables declaration
//methods declaration
}
Variables declared in the class are known as instance variables.
Variables and methods declared within the class are collectively known as members of
the class.
Example
class Rectangle
{
int length;
int breadth;
int area()
{return(length*breadth);}
}
class Outer_Demo {
class Inner_Demo {
}
}
class Outer {
void outerMethod()
{ System.out.println("inside outerMethod");
class Inner {
void innerMethod() { System.out.println("inside innerMethod"); }
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo {
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}
3) Anonymous inner classes
An inner class declared without a class name is known as an anonymous inner class. In
case of anonymous inner classes, we declare and instantiate them at the same time.
Generally, they are used whenever you need to override the method of a class or an
interface. The syntax of an anonymous inner class is as follows –
Syntax
AnonymousInneran_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
Static nested classes
Static nested classes are not technically an inner class. They are like a static member of
outer class.
class Outer {
private static void outerMethod() { System.out.println("inside outerMethod"); }
}
27.Explain constructor in java.
OR
28.What are constructors? How they are invoked in java? Also explain the
different types of constructors.
Constructor is a special method in Java which is used to initialize the object. It looks like
a normal method however it is not. A normal java method will have return type whereas
the constructor will not have an explicit return type. A constructor will be called during
the time of object creation (i.e) when we use new keyword follow by class name.
For Example: Let’s say we have class by the name “Test“, we will create object for Test
class like below
In the below code we have created the no-arg constructor which gets called during the
time of object creation (Car c = new Car())
Car()
String[] args It is an array where each element of it is a string, which has been named as
"args". If your Java program is run through the console, you can pass the input parameter,
and main() method takes it as input.
System.out.println(); This statement is used to print text on the screen as output, where
the system is a predefined class, and out is an object of the PrintWriter class defined in
the system. The method println prints the text on the screen with a new line. You can also
use print() method instead of println() method. All Java statement ends with a semicolon.
We can use a break with the switch We can not use a break with the switch
03. statement. statement.
The break statement terminates the The continue statement brings the next
04. whole loop early. iteration early.
insert(int offset, String s)method: is used to insert the specified string with this string
at the specified position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
System.out.println(sb);//prints HJavaello
replace(int startIndex, int endIndex, String str): is used to replace the string from
specified startIndex and endIndex.
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
delete(int startIndex, int endIndex):is used to delete the string from specified startIndex
and endIndex.
sb.delete(1,3);
System.out.println(sb);//prints Hlo
sb.reverse();
System.out.println(sb);//prints olleH
public intcapacity():is used to return the current capacity.The default capacity of the
buffer is 16. If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
System.out.println(sb.capacity());//default 16
public intlength():is used to return the length of the string i.e. total number of characters.
int p = s.length();
class Student{
int rollno;
String name;
this.rollno=rollno;
this.name=name;
}
36.What is finalize method in java?
It is a method that the Garbage Collector always calls just before the deletion/destroying
the object which is eligible for Garbage Collection, so as to perform clean-up activity.
Clean-up activity means closing the resources associated with that object like Database
Connection, Network Connection or we can say resource de-allocation. Remember it is
not a reserved keyword.
Once the finalize method completes immediately Garbage Collector destroy that object.
finalize method is present in Object class and its syntax is:
protected void finalize throws Throwable{}
37.What is a final variable?
final variables are nothing but constants. We cannot change the value of a final variable
once it is initialized.
A final variable can be explicitly initialized only once. A reference variable declared final
can never be reassigned to refer to a different object.
public class Test {
public static void main(String args[]) {
final int i = 10;
i = 30; // Error because i is final.
}
}
38.What are the uses of super keyword?
The super keyword in Java is a reference to the object of the parent/superclass. Using it,
you can refer/call a field, a method or, a constructor of the immediate superclass.
super can be used to refer immediate parent class instance variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.
Example
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
}
}
41.What the purpose is of extends keyword?
The extends keyword extends a class (indicates that a class is inherited from another
class).
In Java, it is possible to inherit attributes and methods from one class to another.
• The extends is a Java keyword, which is used in inheritance process of Java. It
specifies the super class in a class declaration using extends keyword. It is a
keyword that indicates the parent class that a subclass is inheriting from. In Java,
every class is a subclass ofjava.lang.Object.
• Extends keyword is also used in an interface declaration to specify one or more
super interfaces.
public class A{
class B extends A {
number++; }
}
In this example, we inherit from class A, which means that B will also contain a field
called number. Two or more classes can also be inherited from the same parent class.
Syntax:
class classA
{
// members
}
class classB extends classA
{
//members
}
Example
class Shape{
void draw()
{
System.out.println(“Draw shape”);
}
}
class Circle extends Shape
{
void drawCircle(){
System.out.println(“Draw Circle”);
}
public static void main(String args[])
{
Circle c = new Circle();
c.draw();
c.drawCircle();
}
}
Multilevel Inheritance:
In Multilevel Inheritance a derived class will be inheriting a parent class and as well as
the derived class act as the parent class to other class. As seen in the below diagram.
ClassB inherits the property of ClassA and again ClassB act as a parent for ClassC. In
Short ClassA parent for ClassB and ClassB parent for ClassC.
Syntax:
class classA
{
// members
}
class classB extends classA
{
//members
}
class classC extends classB
{
//members
}
Example
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}
Hierarchical Inheritance:
When one single class is inherited by multiple subclasses is known as hierarchical
inheritance.
As per the below example ClassA will be inherited by ClassB, ClassC and ClassD.
ClassA will be acting as a parent class for ClassB, ClassC and ClassD.
Syntax
class classA
{
// members
}
class classB extends classA
{
//members
}
class classC extends classA
{
//members
}
Example
class Laptop
{
void display()
{
System.out.println(“Working...”);
}
class Dell extends Laptop
{
void print()
{
System.out.println(“Dell Inspiron”);
}
}
class Lenovo extends Laptop
{
void show()
{
System.out.println(“Lenovo YOGA”);
}
}
class TestDemo
{
public static void main(String args[]){
Dell d = new Dell();
d.print();
d.display();
Lenovo l = new Lenovo();
l.show();
l.display();
}
}
Multiple Inheritance
Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented Programming languages
such as Java, Small Talk, C# etc.. (C++ Supports Multiple Inheritance). As the Child
class has to manage the dependency of more than one Parent class. But you can achieve
multiple inheritance in Java using Interfaces.
Example
class visibility
{
int x; //default variable
public int y; //public variable
private int z; // private variable
int data(int a)
{ z=a;
return z; }
}
Class test
{
public static void main(String args[])
{
visibility obj=new visibility();
obj.x=10;
obj.y=20;
int k=obj.data(30);
System.out.println(“x=“+obj.x+”y=“+obj.y+”z=“+k);
}
}
51.What is Package? Explain the steps for creating a package and create a user
defined package.
PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It helps
organize your classes into a folder structure and make it easy to locate and use them.
More importantly, it helps improve code reusability.
Each package in Java has its unique name and organizes its classes and interfaces into a
separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in the same package,
they can appear in different packages. This is possible by assigning a separate namespace
to each Java package.
Syntax: -
package nameOfPackage;
package p1;
class c1(){
obj.m1();} }
Here,To put a class into a package, at the first line of code define package p1.
Next create class c1 with method m1 and call this method using object obj .
javac demo.java
javac –d . demo.java
Step 5) When you execute the code, it creates a package p1. When you open the java
package p1 inside you will see the c1.class file.
javac –d .. demo.java
Step 7) Now let's say you want to create a sub package p2 within our existing java
package p1. Then we will modify our code as
package p1.p2;
class c1{
to Import Package
Syntax
import packageName;
Once imported, you can use the class without mentioning its fully qualified name.
package p3;
import p1.*; //imports classes only in package p1 and NOT in the sub-package p2
class c3{
obj1.m1();
}}
Step 2) Save the file as Demo2.java. Compile the file using the command
javac –d . Demo2.java
java.lang Language support classes. They include classes for primitive types, string, math
functions, thread and exceptions.
java.util Language utility classes such as vectors, hash tables, random numbers, data, etc.
java.io Input/output support classes. They provide facilities for the input and output of data.
java.applet Classes for creating and implementing applets.
java.net Classes for networking. They include classes for communicating with local computers
as well as with internet servers.
java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
There are many differences between method overloading and method overriding in java.
A list of differences between method overloading and method overriding are given
below:
class OverloadingExample{