Java Unit-1 Q&a
Java Unit-1 Q&a
1. Explain in detail. What are java buzz words? Give brief description. (OR)
List and explain the features of Java language?
Java features:
The features of Java are also known as java buzzwords.
A list of most important features of Java language is given below. .
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
1. Simple:
Java is a simple language because its syntax is simple, clean, and easy to understand. Complex and
ambiguous concepts of C++ are either eliminated or re-implemented in Java. For example, pointer and
operator overloading are not used in Java.
2. Object-oriented:
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3. Platform Independent:
Unlike other programming languages such as C, C++ etc which are compiled into platform specific
machines. Java is guaranteed to be write-once, run-anywhere language. On compilation Java program is
compiled into byte code. This byte code is platform independent and can be run on any machine, plus this
byte code format also provides security. Any machine with Java Runtime Environment can run Java
Programs.
4. Secure:
Java is a secure programming language because it has no explicit pointer and programs runs in the virtual
machine. Java contains a security manager that defines the access of Java classes.
5. Multi-Threading:
Java multithreading feature makes it possible to write program that can do many tasks simultaneously.
Benefit of multithreading is that it utilizes same memory and other resources to execute multiple threads at
the same time, like While typing, grammatical errors are checked along.
6. Architectural Neutral:
Compiler generates byte codes, which have nothing to do with particular computer architecture; hence a
Java program is easy to interpret on any machine.
7. Portable:
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't require any
implementation. For example, the size of primitive data types.
8. High Performance:
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++. But, Java
enables high performance with the use of just-in-time compiler.
9. Distributed:
Java is distributed because it facilitates users to create distributed applications in Java. This feature of Java
makes us able to access files by calling the methods from any machine on the internet.
10. Dynamic:
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages, i.e., C and C++. Java supports dynamic compilation and
automatic memory management (garbage collection).
11. Robust:
Java makes an effort to check error at run time and compile time. It uses a strong memory management
system called garbage collector. Exception handling and garbage collection features make it strong.
2. Describe the steps involved in writing and compiling a simple java program, including Creating a
class, define a method, and executing the program.
Magic bytecode
Java's magic bytecode refers to the unique identifier found at the beginning of every compiled Java class
file. This identifier is a sequence of four bytes known as the magic number: 0xCAFEBABE
Purpose of the Magic Number (0xCAFEBABE)
The magic number helps the Java Virtual Machine (JVM) verify that a file is a valid, compiled Java
bytecode file before executing it. This acts as a signature, ensuring that the file can be recognized as a Java
class file by the JVM and is compatible with the execution environment.
Bytecode is the intermediate representation of Java programs that is produced after the source code is
compiled by the javac compiler.
It is platform-independent and can be run on any device that has a Java Virtual Machine (JVM).
The JVM reads the bytecode and translates it into machine code for execution on the specific hardware.
5. Write a java program to read three numbers through the keyboard and find their sum and
average.
Program:
import java.util.Scanner;
public class SumAndAverage
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
double num1, num2, num3;
System.out.print("Enter the first number: ");
num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
num3 = scanner.nextInt();
int sum = num1 + num2 + num3;
double average = sum / 3;
System.out.println("The sum of the numbers is: " + sum);
System.out.println("The average of the numbers is: " + average);
scanner.close();
}
}
Output:
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30
The sum of the numbers is: 60
The average of the numbers is: 20.0
Program:
import java.util.Scanner;
public class Factorial
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to compute its factorial: ");
int number = scanner.nextInt();
int factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial *= i;
}
System.out.println("The factorial of " + number + " is: " + factorial);
scanner.close();
}
}
Output:
Enter a number to compute its factorial: 5
The factorial of 5 is: 120
Program:
import java.util.Scanner;
public class StringReverser
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string to reverse: ");
String str = scanner.nextLine();
String rstr = "";
char ch;
for (int i = 0; i <str.length(); i++)
{
ch=str.charAt(i);
rstr=ch+rstr;
}
System.out.println("Reversed string: " + rstr);
scanner.close();
}
}
Output:
Enter a string to reverse: Java Programming
Reversed string: gnimmargorP avaJ
_______________________________________________________________________________________
8. List the various control statement. Explain any one control statement with the help of
flowchart and example program. (OR)
List and explain the control statements with examples.(OR)
Compare the working of the while loop and do-while loop with suitable examples.(OR)
Explain various types of iterative statements with suitable example.(OR)
Demonstrate Nested if and else using an example.
a) if statement :
The "if" statement is used to evaluate a condition. The control of the program is diverted depending upon
the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java,
there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.
Syntax:
if(condition)
{
statement 1; //executes when condition is true
}
Example:
public class IfTest
{
public static void main(String[] args)
{
int x = 10, y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement:
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition)
{
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}
Example:
public class ElseIfTest
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else statement at the end of the chain.
Syntax:
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
}
Example:
public class ElseIfLadderTest
{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Eluru")
{
System.out.println("city is Eluru");
}
else if (city == "Vijayawada")
{
System.out.println("city is Vijayawada");
}
else if(city == "Hyderabad")
{
System.out.println("city is Hyderabad");
}
else
{
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement:
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax:
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
}
Example:
public class NestedIfTest
{
public static void main(String args[])
{
int x = 30, y = 10;
if( x < 30 )
{
System.out.print("X < 30");
}
else
{
if( y > 9 )
{
System.out.print("X > 30 and Y > 9");
}
}
}
}
Output:
X > 30 and Y > 9
Switch Statement:
Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code
called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements.
The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
.
case valueN:
statementN;
break;
default:
sstatementDefault;
}
Example:
import java.io.*;
class SwitchTest
{
public static void main (String[] args)
{
int num=20;
switch(num)
{
case 5 : System.out.println("It is 5");
break;
case 10 : System.out.println("It is 10");
break;
case 15 : System.out.println("It is 15");
break;
case 20 : System.out.println("It is 20");
break;
default: System.out.println("Not present");
}
}
}
Output:
It is 20
Loop Statements:
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates
to true. However, loop statements are used to execute the set of instructions in a repeated order.
There are three types of loop statements:
1. for loop
2. while loop
3. do-while loop
4. for each loop
1. for loop:
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition,
and increment/decrement in a single line of code. We use the for loop only when we exactly know the
number of times, we want to execute the block of code.
Syntax:
for(initialization, condition, increment/decrement)
{
//block of statements
}
Flowchart:
Example:
class ForTest
{
public static void main(String[] args)
{
int num;
for(num=1;num<=10;num++)
{
System.out.print(num+" " );
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
2. while loop:
The while loop is also used to iterate over the number of statements multiple times. However, if we don't
know the number of iterations in advance, it is recommended to use a while loop. It is also known as the
entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the
loop body will be executed; otherwise, the statements after the loop will be executed.
Syntax:
while(condition)
{
//looping statements
}
Flowchart:
Example:
class WhileTest
{
public static void main(String[] args)
{
int num=1;
While(num<=10)
{
System.out.print(num+" " );
num++;
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
3. do-while loop:
The do-while loop checks the condition at the end of the loop after executing the loop statements. When the
number of iteration is not known and we have to execute the loop at least once, we can use do-while loop. It
is also known as the exit-controlled loop since the condition is not checked in advance.
Syntax:
do
{
//statements
} while (condition);
Example:
class WhileTest
{
public static void main(String[] args)
{
int num=1;
do
{
System.out.print(num+" " );
num++;
} while(num<=10)
}
}
Output:
1 2 3 4 5 6 7 8 9 10
4. for-each loop:
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each
loop, we don't need to update the loop variable.
Syntax:
for(data_type var : array_name/collection_name)
{
//statements
}
Example:
class ForEachTest
{
public static void main(String[] args)
{
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList)
{
System.out.print(i+");
}
}
}
Output:
10 20 30 40 50
Jump Statements:
Jump statements are used to transfer the control of the program to the specific statements. In other words,
jump statements transfer the execution control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.
break statement:
As the name suggests, the break statement is used to break the current flow of the program and transfer the
control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in
the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the
loop or switch statement.
Syntax:
Example:
public class BreakExample
{
public static void main(String[] args)
{
for(int num=1;num<=10;num++)
{
System.out.print(num+" " );
if(i==6)
break;
}
}
}
Output:
1 2 3 4 5 6
continue statement:
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of
the loop and jumps to the next iteration of the loop immediately.
Syntax:
Example:
public class BreakExample
{
public static void main(String[] args)
{
for(int num=1;num<=10;num++)
{
System.out.print(num+" " );
if(i==6)
continue;
}
}
}
Output:
1 2 3 4 5 7 8 9 10
Operators:
A Java operator is a special symbol that performs a certain operation on multiple operands and gives the
result as an output.
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups.
1 Unary Operator
2 Arithmetic Operators
3 Relational Operators
4 Bitwise Operators
5 Logical Operators
6 Assignment Operators
7 Other Operators
1. Unary operators
Unary operators are(+,-,!,~,++,--)
The Java unary operators require only one operand. Unary operators are used to perform various operations
i.e.:
Incrementing/decrementing a value by one
Negating an expression
Inverting the value of a boolean
Example:
public class UnaryOperator
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Output:
10
12
12
10
2. Arithmetic Operators:
Arithmetic Operators are (+, -, *, /, %)
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.
Example:
public class ArithmeticOperators
{
public static void main(String args[])
{
int a=10,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
}
}
Output:
15
5
50
2
0
3. Relational Operators:
Relational operators are = =, !=, <, <=, >, >=. These operators are used to check for relations like equality,
greater than, and less than. They return boolean results after the comparison and are extensively used in
looping statements as well as conditional if-else statements.
Example:
import java.io.*;
class RelationalOperators
{
public static void main(String[] args)
{
int a = 10, b = 3, c = 5;
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
Output:
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
4. Bitwise Operators:
Bitwise operators are &, |, ^, ~.
Bitwise operator works on bits and performs bit-by-bit operation.
Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands.
If both bits are 1, it gives 1. If either of the bits is not 1, it gives 0.
Truth Table:
Bitwise OR:
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands.
If either of the bits is 1, it gives 1. If not, it gives 0.
Truth Table:
Bitwise NOT:
It is also called as Bitwise complement.
It is a unary operator (works on only one operand).
It is denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
Truth Table:
Bitwise XOR:
Bitwise XOR is a binary operator (operates on two operands).
It's denoted by ^.
The ^ operator compares corresponding bits of two operands.
If corresponding bits are different, it gives 1. If corresponding bits are same, it gives 0.
Truth Table:
Here, num specifies the number of positions to left -shift the value in value.
(<<) moves all of the bits in the specified values to the left by the number of bits positions specified by num.
When shifting left, the most-significant bit is lost, and a 0 bit is inserted on the other end.
Here, num specifies the number of positions to right - shift the value in value.
(>>) moves all of the bits in the specified values to the right by the number of bits positions specified by
num.
When shifting right with a right shift, the least-significant bit is lost and a 0 is inserted on the other end.
Example:
import java.io.*;
class BitwiseOperators
{
public static void main(String[] args)
{
int d = 001010;
int e = 001100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}
Output:
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
5. Logical Operators :
Logical operators are &&,||,!.
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
Truth table:
Example:
import java.io.*;
class LogicalOperator
{
public static void main (String[] args)
{
boolean x = true, y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}
Output:
x && y: false
x || y: true
!x: false
6. Assignment Operators:
Assignment operators are +=, -=, *=, /=, %=
Example:
import java.io.*;
class AssignementOperators
{
public static void main(String[] args)
{
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
}
}
Output:
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
7. Other Operators:
There are few other operators supported by Java Language.
i. Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean expressions.
The goal of the operator is to decide, which value should be assigned to the variable.
Syntax: variable x = variable = (condition)?expression1: expression2
The above statement states that if the condition returns true, expression1 gets executed, else
the expression2 gets executed and the final result stored in a variable.
Example:
class ConditionalOperator
{
public static void main(String args[])
{
int num=20;
String result=(num>0) ? ”Positive number” : ”Negative number”;
System.out.println(result);
}
}
Output:
Positive number
ii.instanceof Operator
This operator is used only for object reference variables.
The operator checks whether the object is of a particular type (class type or interface type).
Example:
class InstanceOfOperator
{
public static void main(String args[])
{
String name = "Tanish";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
Output:
true
10. List and explain the Data types in Java program with examples.
String (Class):
Used to store a sequence of characters.
Example: String greeting = "Hello, World!";
Array:
A collection of elements of the same type.
Example: int[] numbers = {1, 2, 3, 4, 5};
Classes and Objects:
Custom data types created by the programmer.
Example:
public class DefaultValuesExample
{
int myInt;
float myFloat;
double myDouble;
char myChar;
boolean myBoolean;
long myLong;
byte myByte;
short myShort;
Tokens: Java tokens are elements of java program which are identified by the compiler.
1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators
6. Comments
7. Separators
1. Keywords
Description: Keywords are reserved words in Java that have a predefined meaning and cannot be
used for any other purpose, such as variable or method names.
2. Identifiers
Description: Identifiers are names given to variables, methods, classes, and other user-defined items.
Rules:
o Must begin with a letter (A-Z or a-z), a dollar sign ($), or an underscore (_).
o Cannot start with a digit and cannot be a keyword.
o Can contain letters, digits, underscores, and dollar signs.
Examples: myVariable, calculateSum, Person, MAX_VALUE.
3. Literals
Description: Literals are fixed values assigned to variables. They are the actual data that identifiers
hold.
Types:
o Integer literals: Whole numbers, e.g., 100, -23.
o Floating-point literals: Numbers with decimal points, e.g., 3.14, 2.5.
o Character literals: A single character within single quotes, e.g., 'A'.
o String literals: A sequence of characters within double quotes, e.g., "Hello".
o Boolean literals: true or false.
4. Operators
Description: Operators are symbols that perform operations on variables and values.
Categories:
o Arithmetic operators: +, -, *, /, %.
o Relational operators: ==, !=, >, <, >=, <=.
o Logical operators: &&, ||, !.
o Assignment operators: =, +=, -=, *=, /=, %=.
o Bitwise operators: &, |, ^, ~, <<, >>, >>>.
5. Separators (Delimiters)
Description: Separators, or delimiters, are symbols that separate code elements to define the
structure and scope.
Examples:
o Parentheses () - Used for grouping expressions and defining method parameters.
o Curly Braces {} - Define blocks of code, like classes, methods, and loops.
o Square Brackets [] - Denote array types and elements.
o Semicolon ; - Ends statements.
o Comma , - Separates items in a list, such as arguments in a method call.
o Dot . - Accesses members of classes or packages.
6. Comments
Description: Comments are non-executable parts of code that provide explanations and are ignored
by the compiler.
Types:
o Single-line comments: Begin with // and extend to the end of the line.
o Multi-line comments: Enclosed within /* ... */.
o Documentation comments: Begin with /** and are used for generating documentation.
7. Special Symbols
12. What do you understand by type casting & automatic promotion? Explain with suitable
examples.(OR)
Demonstrate implicit and explicit type casting with an example program.
Type casting: It is a method or process that converts a data type into another data type in both ways
manually and automatically.
The automatic conversion is done by the compiler and manual conversion performed by the programmer.
Example:
class ImplicitExample
{
public static void main(String[] args)
{
int a = 10;
System.out.println("Int value is:"+a);
double b = a;
System.out.println("Double valueis: "+b);
}
}
Output:
Int value is: 10
Double value is: 10.0
Example:
class ExplicitExample
{
public static void main(String[] args)
{
double d =6.865 ;
System.out.println("Double value is: "+d);
int a = (int) d;
System.out.println("Int value is: "+a);
}
}
Output:
Double value is: 6.865
Int value is: 6
13. What is a variable? Explain their importance in java language. What rules to be followed to
define them?(OR)
Explain the type and behavior of Java variables.
Variable:
A variable is a container which holds the value while the Java program is executed.
A variable is assigned with a data type.
Variable is a name of memory location.
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
All variable must be declared before they can be used in java.
A variable is defined by the combination of an variable name, a type, and an optional initializer.
Types of Variables:
There are three types of variables in Java
1. local variable 2. instance variable 3. static variable
1. Local Variable:
A variable declared inside the body of the method is called local variable.
We can use this variable only within that method and the other methods in the class.
A local variable cannot be defined with "static" keyword.
2. Instance variable
A variable declared inside the class but outside the body of the method, is called instance variable.
It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3. Static variable:
A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the memory.
Example:
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Importance of variables:
Data Storage: Variables hold data values (like numbers, text) that our program needs to work with.
Readable Code: Using clear variable names makes our code easier to understand.
Reusability: Variables can store values we use repeatedly, so we don’t have to write the same value
in many places.
Dynamic Data: Variables let us work with changing data (like user input or calculations) during a
program’s run.
Memory Management: By choosing variable types, we control how much memory our data uses.
Easier Updates: Instead of changing values everywhere in the code, we just update the variable's
value.
Parameter Passing: Variables allow us to send values into methods, making our code modular and
reusable.
Object-Oriented Design: Variables define object attributes, helping represent real-world entities like
"Car" with properties like "color" or "speed."
15. Describe how command-line arguments are passed to a java program and accessed within the
program.
Example:
Class A
{
Public static void main(String args[])
{
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
Output:
_______________________________________________________________________________________
16. Explain the usage of Static variables and methods with an example Java program.
Static variable:
The variables that are created common to all the objects are called static variables/class variables.
The static variables belong to the class as a whole rather than the objects.
It is mainly used when we need to count no of objects created for the class.
The non-static variables declared in a class are instance variables Each object of the class keeps a
copy of the values of these variables.
Static methods:
A static method is a method that does not act upon instance variables of a class.
A static method is declared by using the keyword static.
Static methods are called using classname.methodName().
The reason why static methods cannot act on instance variables is that JVM first loads static
elements of the .class file one specific memory location inside the RAM and then searches for the
main method, and then only it creates the objects
Since objects are not available at the time calling static methods, the instance variables are also not
available at the time of calling the static methods.
Static methods are also called as class methods.
They cannot refer to this or super keywords (super used in inheritance).
Example:
class Example
{
static int number = 5;
static void displayNumber()
{
System.out.println("The value of number is: " + number);
}
}
17. Discuss the use of escape sequences in java strings for representing special characters.
Example:
class EscapeSequence
{
public static void main(String[] args)
{
System.out.println("Escape Sequence Character in \"Java\" ");
System.out.println("Escape Sequence Character in \t Java ");
System.out.println("Escape Sequence Character in\b Java ");
System.out.println("Escape Sequence Character in \n Java ");
System.out.println("HAI \r JAVA"); // HAI is skipped and prints only JAVA
System.out.println("Escape Sequence Character in \f Java");
System.out.println("Escape Sequence Character in \'Java\' ");
System.out.println("\\- Escape Sequence Character in ");
}
}
Output:
Escape Sequence Character in "Java"
Escape Sequence Character in Java
Escape Sequence Character i Java
Escape Sequence Character in
Java
JAVA
Escape Sequence Character in
Java
Escape Sequence Character in 'Java'
\- Escape Sequence Character in
___________________________________________________________________________________________
18. What is Java? Describe the Basic rules to define java identifiers.
19. List and explain the formatted input and output statements.
20. Illustrate the difference between java & C++. Why is Java language important in relevance to the
Internet?
Java and C++ share similarities as object-oriented languages, but they also have significant differences in
design, features, and usage.
Platform-
C++ is platform-dependent. Java is platform-independent.
independent
C++ was designed for Java was designed and created as an interpreter
systems and applications for printing systems but later extended as a
Design Goal programming. It was an support network computing. It was designed to
extension of the C be easy to use and accessible to a broader
programming language. audience.
C++ supports
Goto Java doesn't support the goto statement.
the goto statement.
Java doesn't support multiple inheritance
C++ supports multiple
Multiple inheritance through class. It can be achieved by
inheritance.
using interfaces in java.
C++ supports pointers. You Java supports pointer internally. However, you
Pointers can write a pointer program can't write the pointer program in java. It means
in C++. java has restricted pointer support in java.
C++ uses compiler only. C++ Java uses both compiler and interpreter. Java
is compiled and run using the source code is converted into bytecode at
Compiler and compiler which converts compilation time. The interpreter executes this
Interpreter source code into machine bytecode at runtime and produces output. Java is
code so, C++ is platform interpreted that is why it is platform-
dependent. independent.
Call by Value and C++ supports both call by Java supports call by value only. There is no call
Call by reference value and call by reference. by reference in java.