Answers - Java (1)
Answers - Java (1)
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.
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.
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
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.
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
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.
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 {
// Main method
// 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.
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.
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;
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;
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.
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:
= 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
== Equal to x == y
!= Not equal 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:
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
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;
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) {
Output:
Leap year
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
A single dimensional array of Java is a normal array where, the array contains sequential elements (of same
type).
Example:
public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
}}
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:
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.
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 :
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
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
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";
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
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;
// 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.