0% found this document useful (0 votes)
2 views29 pages

Answers - Java (1)

The document outlines key features of Java, such as its simplicity, security, portability, and object-oriented nature, which contribute to its popularity. It also discusses Java tokens, variable scope and lifetime, jumping statements, and provides examples of Java programs for various functionalities. Additionally, it explains Java operators and their categories, emphasizing the language's versatility and robustness.

Uploaded by

Sakshi Damani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Answers - Java (1)

The document outlines key features of Java, such as its simplicity, security, portability, and object-oriented nature, which contribute to its popularity. It also discusses Java tokens, variable scope and lifetime, jumping statements, and provides examples of Java programs for various functionalities. Additionally, it explains Java operators and their categories, emphasizing the language's versatility and robustness.

Uploaded by

Sakshi Damani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

1. List out Java features in detail and justify how it helps to java to became a popular one.

Java Features or Java Buzzwords

Simple:
•Java easy to learn
•It is easy to write programs using Java
•Expressiveness is more in Java.
•Most of the complex or confusing features in C++ are removed in Java like pointers etc..

Secure:
•Java provides data security through encapsulation.
•Also we can write applets in Java which provides security.
•An applet is a small program which can be downloaded from one computer to another
automatically.
•There is no need to worry about applets accessing the system resources which may
compromise security.
•Applets are run within the JVM which protects from unauthorized or illegal access to system
resources.

Portable:
•Applications written using Java are portable in the sense that they can be executed on any
kind of computer containing any CPU or any operating system.
•When an application written in Java is compiled, it generates an intermediate code file called as “bytecode”.
•Bytecode helps Java to achieve portability.
•This bytecode can be taken to any computer and executed directly.

Object - Oriented:
•Java follows object oriented model.
•So, it supports all the features of object oriented model like:
Encapsulation Inheritance Polymorphism Abstraction
Robust:
•A program or an application is said to be robust(reliable) when it is able to give some
response in any kind of context.
•Java’s features help to make the programs robust. Some of those features are:
Type checking
Exception handling

Multithreaded:
•Java supports multithreading which is not supported by C and C++.
•A thread is a light weight process.
•Multithreading increases CPU efficiency.
•A program can be divided into several threads and each thread can be executed concurrently
or in parallel with the other threads.
•Real world example for multithreading is computer. While we are listening to music, at the
same time we can write in a word document or play a game.

Architecture - Neutral:
•Bytecode helps Java to achieve portability.
•Bytecode can be executed on computers having any kind of operating system or any kind of
CPU.
•Since Java applications can run on any kind of CPU, Java is architecture – neutral.

Interpreted and High Performance:


•In Java 1.0 version there is an interpreter for executing the bytecode. As interpreter is quite slow when
compared to a compiler, java programs used to execute slowly.
•After Java 1.0 version the interpreter was replaced with JIT(Just-In-Time) compiler.
•JIT compiler uses Sun Microsystem’s Hot Spot technology.
•JIT compiler converts the byte code into machine code piece by piece and caches them for
future use.
•This enhances the program performance means it executes rapidly.
Distributed:
•Java supports distributed computation using Remote Method Invocation (RMI) concept.
•The server and client(s) can communicate with another and the computations can be divided
among several computers which makes the programs to execute rapidly.
•In distributed systems, resources are shared.
Dynamic:
•The Java Virtual Machine(JVM) maintains a lot of runtime information about the program
and the objects in the program.
•Libraries are dynamically linked during runtime.
•So, even if you make dynamic changes to pieces of code, the program is not affected.

Reason why JAVA became popular:


•Java was initially codenamed(called) “Oak”. Later it became Java.
•The reason why Java became popular was not because of the embedded systems.There was
another reason.
•When Java was developed in 1991, there was another force which was changing the world rapidly. It was
“Internet”.
•Internet is a collection of computers located at various locations which are interconnected
through communication links.
•So, each computer has its own CPU and hardware. Again it was the same problem of
developing platform-independent applications.
•Since Java was already developed to solve this problem , it was also used to develop
programs which can run on the internet.
•Thus Java attained a wide spread popularity as a programming language because of the
Internet.

Mention the available java lexical issues/tokens with example


Lexical Issues/Java Tokens:
Java Tokens are the smallest individual building block or smallest unit of a Java program;
The Java compiler uses it for constructing expressions and statements.
Java programs are a collection of
White spaces ,
Identifiers ,
comments ,
Literals ,
Operators ,
Separators and
Keywords

White Spaces
Java is a free form language. This means that you do not need to follow any special indentation rules. In java ,
white spaces is a space , tab or new line.

Identifiers

Identifiers are used for class names , method names and variable names. An identifier may be any descriptive
sequence of uppercase and lowercase letters , numbers or the underscore and dollar sign design.

Rules for Identifiers in Java:

A valid identifier has characters [A-Z],[a-z] or numbers [0-9], $ (dollar sign) and _ (underscore).
Can have any combination of characters after the first character.
Cannot be a keyword.

Example:
Int area_circle;//area_circle is valid identifier.

Float @dataflair; //It is not a valid identifier, because it contains @ which is a special character.
We can't declare a variable with space. For example, int data flair is invalid

Literals

A constant value in java is created by using a literal representation of it. A literal can be used anywhere a
value of its type is allowed.
Types of Literals Integer Literals
Integer Literals are numbers that has no fractional pars or exponent. It refers to the whole
numbers. Integers always begin with a digit or + or -.
We can specify integer constants in
Decimal
Octal
Hexadecimal
Decimal Integer Literals
It consists of any combination of digits taken from the set 0 to 9. Example:
int a = 100; //Decimal Constant

Octal Integer Literals


It consists of any combination of digits taken from the set 0 to 7. However the first digit must be 0, in order to
identify the constant as octal number.
Example:
int a = 0374; //Octal Constant
int b = 097; // Error: 9 is not an octal digit.

Hexadecimal Integer Literals


A Sequence of digits begin the specification with 0X or 0X, shadowed by a system of digits in the range 0 to 9
and A (a) to F(f).
Example:
int a = 0x34; int b = -0XABF;

Floating-point Literals
Floating-point Literals are also called as real constants. The Floating Point contains decimal points and can
contain exponents. They are used to represent values that will have a fractional part and can be represented in
two forms – fractional form and exponent form.
In the fractional form, the fractional number contains the integer part and fractional part. A dot (.) is used to
separate the integer part and fractional part.
Example:
float x = 2.7f;
Character Literals
Character Literals are specified as single character enclosed in pair of single quotation marks. Single character
constants are internally represented as ASCII codes.
String Literals
String Literals are treated as an array of char. By default, the compiler adds a special character
called the ‘null character’ (‘\0’) at the end of the string to mark the end of the string.
Example:
String str = “good morning”;

Boolean literals
There are two Boolean literals
true represents a true Boolean value
false represents a false Boolean value

Comments

Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent
execution when testing alternative code.

There are 3 types of comment in java.


single line comment - //
Multi line comment. - /* …..
…… */
Documentation comment. - a/** a*/.
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be executed). This example uses a
single-line comment before a line of code: System.out.println("Hello World"); // This is a comment
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:
/* The code below will print the words Hello World to the screen, and it is amazing */
System.out.println("Hello World");

Documentation comment. - It is used to produce an HTML file that documents your program. It begins with
a/** and ends with a*/.

Separators

There are few symbols in java that are used as separators.The most commonly used separator in java is the
semicolon ' ; '. some other separators are Parentheses '( )' , Braces ' {} '
, Bracket ' [] ' , Comma ' , ' , Period ' . ' .

Java Keywords

Java has a set of keywords that are reserved words that cannot be used as variables, methods, classes, or any
other identifiers

The Keywords are :

abstract , assert , boolean , break , byte , case , catch , char , class , const , continue , default , do , double , else
, extends , final , finally , float , for , if , implements , import , instanceof , int,interface , long , native , new ,
package , private , protected , public , return , short , static , strictfp , super , switch , synchronized , this ,
throw , throws , transient , try , void , volatile, while.

Scope and Lifetime of a variable. Give example code

What is variable?
A variable is only a name given to a memory location, all the operations done on the variable effects that
memory location
Scope and lifetime of variables:
The scope of a variable refers to the areas or the sections of the program in which the variable can be
accessed, and the lifetime of a variable indicates how long the variable stays alive in the memory.
The scope and lifetime of a variable is “how and where the variable is defined.”
Instance Variables
A variable which is declared inside a class and outside all the methods and blocks is an instance variable. The
general scope of an instance variable is throughout the class except in static methods. The lifetime of an
instance variable is until the object stays in memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked static is known as a class
variable. The general scope of a class variable is throughout the class and the lifetime of a class variable is
until the end of the program or as long as the class is loaded in memory.
Local Variables
All other variables which are not instance and class variables are treated as local variables including the
parameters in a method. Scope of a local variable is within the block in which it is declared and the lifetime of
a local variable is until the control leaves the block in which it is declared.

Example:
Java Program: Local, Static, and Instance Variables
public class VariableDemo {

// Static variable (shared by all objects) static int staticCount = 0;


// Instance variable (unique for each object) int instanceCount = 0;
// Method to demonstrate variable types void showVariableTypes() {
// Local variable (declared inside a method) int localValue = 100;
// Modify static and instance variables staticCount++;
instanceCount++;

// Display all variable values

System.out.println("Local Variable (localValue): " + localValue);


System.out.println("Static Variable (staticCount): " + staticCount); System.out.println("Instance Variable
(instanceCount): " + instanceCount);
}

// Main method

public static void main(String[] args) {

// Create two objects of VariableDemo VariableDemo obj1 = new VariableDemo(); VariableDemo obj2 = new
VariableDemo();
// Call method using first object System.out.println("Object 1:"); obj1.showVariableTypes();
// Call method using second object System.out.println("Object 2:"); obj2.showVariableTypes();
}
}

Output:

Object 1:

Local Variable (localValue): 100 Static Variable (staticCount): 1 Instance Variable (instanceCount): 1 Object
2:
Local Variable (localValue): 100 Static Variable (staticCount): 2 Instance Variable (instanceCount): 1
Explanation:
localValue is local – it is recreated each time the method runs.
staticCount is static – it keeps incrementing across all objects.
instanceCount is instance – each object gets its own copy.

Short note on jumping statements with example

Jumping Statements

Branching statements jump from one statement to another and transfer the execution flow. There are 3
branching statements in Java.

Break
Continue
return
Break

Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in
loop to stop the execution and comes out of loop. When there are nested loops then break will terminate the
innermost loop.

Syntax:

jump-statement; break;
Data Flow Diagram of break statement

Example:

class breakTest
{
public static void main(String args[])
{
for (int j = 0; j < 5; j++)
{
// come out of loop when i is 4. if (j == 4)
break;
System.out.println(j);
}
System.out.println("After loop");
}
}

Output:

0
1
2
3
4
After loop

Continue

Continue statement works same as break but the difference is it only comes out of loop for that iteration and
continue to execute the code for next iterations. So it only bypasses the current iteration.

Syntax:

jump-statement; continue;

Example:

class continueTest
{
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
// If the number is odd then bypass and continue with next value if (j%2 != 0)
continue;
// only even numbers will be printed System.out.print(j + " ");
}
}
}

Output:

02468

Return

Return statement is used to transfer the control back to calling method. Compiler will always bypass any
sentences after return statement. So, it must be at the end of any method. They can also return a value to the
calling method.

Example: Here method getwebURL() returns the current URL to the caller method.

public String getwebURL()


{
String vURL= null; try {
vURL= driver.getCurrentUrl();
}
catch(Exception e)
{
System.out.println("Exceptionoccured while getting the current url : "+e.getStackTrace());
}
return vURL;
}
Write a java program to print an array value and display the same value in reverse order using array.

public class ReverseArray {


public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};

System.out.println("Original Array:");
for(int i : arr)
System.out.print(i + " ");

System.out.println("\nReversed Array:");
for(int i = arr.length - 1; i >= 0; i--)
System.out.print(arr[i] + " ");
}
}

Write a java program to print the day name of the week using appropriate switch case

import java.util.Scanner;

public class DayName {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter day number (1-7): ");
int day = sc.nextInt();

switch(day) {
case 1: System.out.println("Sunday"); break;
case 2: System.out.println("Monday"); break;
case 3: System.out.println("Tuesday"); break;
case 4: System.out.println("Wednesday"); break;
case 5: System.out.println("Thursday"); break;
case 6: System.out.println("Friday"); break;
case 7: System.out.println("Saturday"); break;
default: System.out.println("Invalid Day!");
}
}
}

write a program for calculating student grade using appropriate control statements.

import java.util.Scanner;

public class StudentGrade {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter student marks: ");
int marks = sc.nextInt();

if(marks < 50)


System.out.println("Fail");
else if(marks < 60)
System.out.println("D Grade");
else if(marks < 70)
System.out.println("C Grade");
else if(marks < 80)
System.out.println("B Grade");
else if(marks < 90)
System.out.println("A Grade");
else if(marks <= 100)
System.out.println("A+ Grade");
else
System.out.println("Invalid marks");
}
}

Briefly explain Java Operators

Operators are special symbols (characters) that carry out operations on operands (variables and values).
For example, is an operator that performs addition.
+
Java divides the operators into the following groups:

Arithmetic operators
Assignment operators
Comparison / Relational operators
Logical operators
Increment and Decrement Operator
Ternary/Conditional Operator

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication,
etc.

Operator Meaning Example

+ Addition (also used for string concatenation) x+y

- Subtraction Operator x-y

* Multiplication Operator x*y

/ Division Operator x/y


% Remainder Operator x%y

Example:

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15 System.out.println(a-b); //5 System.out.println(a*b);
//50 System.out.println(a/b); //2 System.out.println(a%b); //0
}
}
Assignment Operators

Assignment operators are used to assign values to variables. Example: int x = 10;
A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3


Comparison/Relational Operators

Comparison/Relational operators are used to compare two values:

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Equality and relational operators are used in decision making and loops

Logical Operators

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Increment and Decrement Operator

You can also use ++ and -- operator as both prefix and postfix in Java. The ++ operator increases value by 1
and -- operator decreases the value by 1.

Example:

int myInt = 5;

++myInt // myInt becomes 6 myInt++ // myInt becomes 7


--myInt // myInt becomes 6
myInt-- // myInt becomes 5

Ternary/Conditional Operator

The conditional operator or ternary operator (?:) is shorthand for the if-then-else statement. The syntax of the
conditional operator is:
variable = Expression ? expression1 : expression2

If the Expression is true, expression1 is assigned to the variable. If the Expression is false, expression2 is
assigned to the variable. Example:
class ConditionalOperator {
public static void main(String[] args) {

int februaryDays = 29; String result;

result = (februaryDays == 28) ? "Not a leap year" : "Leap year"; System.out.println(result);


}
}

Output:

Leap year

What is Arrays? Types of arrays with example

An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work
differently than they do in C/C++. Following are some important point about Java arrays.
In Java all arrays are dynamically allocated.
Since arrays are objects in Java, we can find their length using member length. This is different from C/C++
where we find length using sizeof.
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered and each have an index beginning from 0.
Java array can be also be used as a static field, a local variable or a method parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Every array type implements the interfaces Cloneable and java.io.Serializable.

Array can contains primitives (int, char, etc) as well as object (or non-primitives) references of a class
depending on the definition of array. In case of primitives data types, the actual
values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in
heap segment.
The general form of array declaration is

type var-name[]; OR
type[] var-name;

Types of Arrays
There are two types of arrays in Java. They are (i)Single Dimensional array and
Multi-Dimensional Array

Single Dimensional Array

A single dimensional array of Java is a normal array where, the array contains sequential elements (of same
type).

Example:

int[] myArray = {10, 20, 30, 40}; Program:


public class TestArray {

public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements

for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " ");


}
// Summing all elements double total = 0;
for (int i = 0; i < myList.length; i++) { total += myList[i];
}

System.out.println("Total is " + total);

// Finding the largest element double max = myList[0];


for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i];
}

System.out.println("Max is " + max);

}}

Output:

1.9

2.9

3.4

3.5

Total is 11.7

Max is 3.5

Multi-Dimensional Array

A multi-dimensional array in Java is an array of arrays. A two dimensional array is an array of one
dimensional arrays and a three dimensional array is an array of two dimensional arrays.
Program:

public class Tester {

public static void main(String[] args) {

int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} }; for(int i = 0 ; i < 3 ; i++){


//row

for(int j = 0 ; j < 2; j++){ System.out.print(multidimensionalArray[i][j] + " ");


}

System.out.println();

} }

Output:

12

23

34

short note on byte streams and write the subclasses with available methods.

Byte stream:
Java Byte streams are used to perform input and output of 8-bit bytes. Byte stream is defined by using two
abstract class at the top of hierarchy, they are InputStream and OutputStream. For example FileInputStream is
used to read from source and FileOutputStream to write to the destination.

Sub classes for Input Stream and Output Stream


Input streams - for reading data from streams

Input Stream Class in Java. InputStream class is the superclass of all the io classes i.e. representing an input
stream of bytes. It represents input stream of bytes. Applications that are defining subclass of InputStream
must provide method, returning the next byte of input
Input stream Constructor :

InputStream() : Single Constructor


Method in Input Stream

Output Stream

OutputStream class is the superclass of all classes representing an output stream of bytes. An output stream
accepts output bytes and sends them to some sink.Applications that need to define a subclass of OutputStream
must always provide at least a method that writes one byte of output.
Output Stream constructor

OutputStream() : Single Constructor

Methods in Output Stream

void close() : Closes this output stream and releases any system resources associated with this stream
void flush() : Flushes this output stream and forces any buffered output bytes to be written output
void write(byte[] b) : Writes b.length bytes from the specified byte array to this output stream
void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this
output stream.
abstract void write(int b) : Writes the specified byte to this output stream

Illustrate Class and object with suitable example


Class Fundamentals
In Java, everything is encapsulated under classes. Class can be defined as a template/blueprint that describes
the behaviors/states of a particular entity. A class defines new data type. Once defined, this new type can be
used to create object of that type. Object is an instance of class. You may also call it as physical existence of a
logical template class.
A class is declared using class keyword. A class contains both data and code that operate on that data. The
data or variables defined within a class are called instance variables and the code that operated on this data
is known as methods.
The General Form of a Class
class classname [ extends baseclass implements interface1, interface2 ]
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}

type methodname2(parameter-list)
{
// body of method
}

// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Rules for Java Class
A Class can have only public or default(no modifier) access specifier.
It must have the class keyword, and class must be followed by a legal identifier.
It may optionally extend one parent class. By default, it will extend java.lang.Object
It may optionally implement any number of comma-separated interfaces.
The class’s variables and methods are declared within a set of curly braces {}
Each .java source file may contain only one public class.
Finally the source file name must match the public class name and it must have a .java suffix.
Objects
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -
wagging, barking, eating. An object is an instance of a class.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name and object type.
Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
The general syntax for declaring object
classname ref_var;
ref_var = new classname ( );
Here, ref_var is a variable of the class type being created. The classname is the name of the class that is being
instantiated. After the first line executes, ref_var contains the value null, which indicates that it does not yet
point to an actual object. The next line allocates an actual object and assigns a reference to it to ref_var.
The new operator dynamically allocates memory for an object. The class name followed by parentheses
specifies the constructer for the class. A constructer defines what occurs when an object of a class is created.
class Pencil
{
private String color = "red";

public void setColor (String newColor) {


color = newColor;
}
public String getColor(){
return color;
}
public static void main(String[] args)
{
Pencil p = new Pencil(); //Object creation
p.setColor("red");
System.out.println("Pencil color is "+p.getColor());
}
}

Explain Constructor and constructor overloading with example


Constructors
A constructor is a special method that is used to initialize an object upon creation.
Constructors have the same name as class name in which it resides.
They have zero or more parameters.
Characteristics of Constructors
Constructors cannot be private.
Constructor in java cannot be abstract, static, final or synchronized. These modifiers are not allowed for
constructors.
Constructors cannot be inherited.
Constructors are automatically called when an object is created.
A constructor does not have any return type, not even void.
Constructors can be overloaded. (i.e) A class can have more than one constructors
Every class has a constructor. If you don’t explicitly declare a constructor for a java class, the compiler builds
a default constructor for that class.
Overloading Constructors
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of
their type of parameters or number of parameters. Constructor overloading is not much different than method
overloading.
Example
class Point
{
private int x,y;
Point() //default constructor
{
x = y = 0;
}
Point(int i, int j) //parameterized constructor with 2 argument
{
x = i;
y = j;
}
public void display()
{
System.out.println(x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point();
Point p2 = new Point(10,20);
p1.display();
p2.display();
}
}
Output
0, 0
10, 20

Discuss in detail about garbage collection with finalize method using example program.
Introduction to Garbage Collection
In Java, destruction of object from memory is done automatically by the JVM. When there is no reference to
an object then that object is assumed to be no longer needed and memory occupied by the object is released.
This technique is known as Garbage Collection.
Advantage of Garbage Collection
Programmer doesn’t need to worry about dereferencing an object
Increases Memory efficiency and decreases the chance of memory leak
It is done automatically by JVM
There are many ways to deference an object:
By nulling the reference
By assigning a reference to another
By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in
System and Runtime classes.
public static void gc(){}
Example
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output
object is garbage collected
object is garbage collected

Using finalize() Method


Sometimes an object will need to perform some clean up task (such as closing an open connection or releasing
any resources held) before it is destroyed. By using finalization, we can define specific actions to occur, just
before it is garbage collected.
To add a finalizer to a class, simply define finalize() method as follow
protected void finalize()
{
//code
}
Example
public class JavafinalizeExample {
public static void main(String[] args)
{
JavafinalizeExample obj = new JavafinalizeExample();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");
}
protected void finalize()
{
System.out.println("finalize method called");
}
}

Output
2018699554
end of garbage collection
finalize method called

Write a program to represent the state and behaviour of the car entity
✅ States (represented using variables):
brand
color
speed
✅ Behaviors (represented using methods):
start()
accelerate()
brake()
displayDetails()
Java Program: Car Entity
public class Car {
// State (attributes)
String brand;
String color;
int speed;

// Constructor to initialize the car


public Car(String brand, String color) {
this.brand = brand;
this.color = color;
this.speed = 0; // car is initially stopped
}

// Behavior 1: Start the car


void start() {
speed = 10;
System.out.println(brand + " is starting with speed " + speed + " km/h");
}

// Behavior 2: Accelerate the car


void accelerate() {
speed += 20;
System.out.println(brand + " is accelerating. Current speed: " + speed + " km/h");
}

// Behavior 3: Apply brake


void brake() {
speed = 0;
System.out.println(brand + " has stopped.");
}

// Behavior 4: Display car details


void displayDetails() {
System.out.println("Car Brand: " + brand);
System.out.println("Car Color: " + color);
System.out.println("Current Speed: " + speed + " km/h");
}

// Main method
public static void main(String[] args) {
// Create a Car object
Car myCar = new Car("Toyota", "Red");

// Show behavior
myCar.displayDetails();
myCar.start();
myCar.accelerate();
myCar.brake();
}
}
Output:
Car Brand: Toyota
Car Color: Red
Current Speed: 0 km/h
Toyota is starting with speed 10 km/h
Toyota is accelerating. Current speed: 30 km/h
Toyota has stopped.

You might also like