0% found this document useful (0 votes)
20 views36 pages

Java Unit-1 Q&a

The document outlines the features of the Java programming language, known as Java buzzwords, including simplicity, object-orientation, portability, and security. It also describes the structure of a Java program, the main method, and the concepts of JDK, JRE, and JVM. Additionally, it provides sample Java programs for calculating the sum and average of numbers, computing factorials, and reversing strings, along with explanations of control statements in Java.

Uploaded by

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

Java Unit-1 Q&a

The document outlines the features of the Java programming language, known as Java buzzwords, including simplicity, object-orientation, portability, and security. It also describes the structure of a Java program, the main method, and the concepts of JDK, JRE, and JVM. Additionally, it provides sample Java programs for calculating the sum and average of numbers, computing factorials, and reversing strings, along with explanations of control statements in Java.

Uploaded by

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

UNIT-1

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.

Structure of Java Program:


Documentation Section: Documentation Section consists of a set of comment lines giving name of the
program, author name and other details optionally which programmer like to use later. These comment lines
are optional Ignored by compiler during program execution.
Ex: /* Addition of 2 numbers in java */
Package statement: Package statement placed just after documentation section. In this section we can
declare user defined packages this is optional section and note that there is only one package statement in
java program
Ex: package mypackage;
Import Statements: A package may contain many predefined classes and interfaces. If we want to use any
of them in our program we need to import that class. It is also optional
Ex: import java.util.Scanner; or import java.util.*;
Interface Statements: A java program may contain interfaces are used to achieve 100% abstraction in java.
It is also optional
Ex: interface Interface1
{
}
Class without main () method: This contains instance variables and methods in it. We can also write
main() method here. (then there is no need of class with main() section)
class Sample
{
int a,b; // instance variables
void fun() //methods
{
int x,y; // local variable
}
}
Class with main() method: This section is mandatory because it contain main() method. Every java
program’s execution starts from main function only. Its Essential.
Ex: class Mainclass
{
public static void main(String args[])
{
……
}
}
Sample Java Program:
class Sample
{
public static void main(String args[])
{
System.out.println("Hello,World");
}
}

Compiling the program:


Javac classname.java
Ex: C:> javac Sample.java
javac is a compiler, which creates a file called Sample.class(contains the bytecode).
Executing the program:
Java classname
Ex:C:> java Sample
java is interpreter which accepts .class file name as a command line argument.
That’s why the name of the source code file and class name should be equal, which avoids the confusion.
Output:
Hello,World

3. Explain main( ) method in java. What is java’s magic byte code?

public static void main(String args[]):


public:
The keyword public is an access specifier that declares the main method as unprotected and therefore
making it accessible to all other classes. The opposite of public is private.
Static:
The keyword static allows main() to be called without creating any instance of that class. This is necessary
because main() is called by java interpreter before creating any object.
Void:
The keyword void tells the compiler that main() does not return any value.
main():
main() is the method called when a java application begins.
String args[]:
Any information that you pass to a method is received by variables specified with in the set of parenthesis
that follow the name of the method. These variables are called parameters. Here args[] is the name of the
parameter of string type.
System.out.println:
It is equal to printf() or cout<<, since java is a true object oriented language, every method must be part of
an object.
The println method is a member of out object, which is a static data member of System class.
Note: println always appends a newline character to the end of the string. So the next println prints the
statements in next line.

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.

4. Explain the concepts JDK, JRE and JVM.


The Java Virtual Machine (JVM), Java Development Kit (JDK), and Java Runtime Environment (JRE) are
three components of the Java development process.

Java Virtual Machine (JVM):


The core of Java programming, the JVM loads, verifies, and runs Java bytecode. It also converts bytecode
to machine-specific code. The JVM is platform-independent, meaning that it can be executed on any
machine that understands the bytecode.
Java Runtime Environment (JRE):
The JRE is a set of software tools that executes Java programs on your system. It includes the JVM, class
libraries, and other components. The JRE is required to run Java applications.
Java Development Kit (JDK):
The JDK is a software development kit used to develop Java applications. It includes the JRE, as well as
development tools like the Java Debugger, JavaDoc, and compilers. The JDK is used for development,
while the JRE is used to run Java applications

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

6. Develop a program to compute factorial of a given number.

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

7. Develop a Java program to perform string reverse operations.

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.

Control Statements In Java:


A statement is defined as an instruction given to the computer to perform specific operations. A control
statement in java is a statement that determines whether the other statements will be executed or not. It
controls the flow of a program.
Control Statements can be divided into three categories, namely

1. Decision Making statements /Selection Statements:


As the name suggests, decision-making statements decide which statement to execute and when. Decision-
making statements evaluate the Boolean expression and control the program flow depending upon the result
of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and
switch statement.

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.

Points to be noted about switch statement:

 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

9. Explain various types of Operators with example. (OR)


Demonstrate Bitwise operators using a Java program. (OR)
With the help of example program explain the various arithmetic operators supported by java
language.(OR)
Demonstrate the Increment and Decrement operators with a Java program. (OR)
List and explain the Unary, Binary and Ternary operators with examples.(OR)
Demonstrate logical operators with an example Java program.

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:

Bit Shift Operators:


A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left.
Bit shift Operators are as follows
1. Left Shift (<<)
2. Right Shift (>>)

1. Left Shift Operators:


The left shift operators (<<) shifts all of the bits in a value to the left a specified number of times.

Syntax :- value << num

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.

2. Right Shift Operators:


The Right shift operators (>>) shifts all of the bits in a value to the right a specified number of times.

Syntax: - value >> num

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).

Syntax: (Object reference variable ) instanceof (class/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.

Data Types in Java:


Data types specify the different sizes and values that can be stored in the variable. There are two types of data
types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are the most basic
data types available in Java language.
There are 8 types of primitive data types.

1. boolean Data Type :


 The Boolean data type is used to store only two possible values: true and false.
 Boolean data type variable are used in the dealing with logical statements.
 Its default value is false.
 Example: boolean one = false
2. byte Data Type
 It is an 8-bit signed integer. That is 1 byte
 Its value-range lies between -128 to 127.
 Its default value is 0.
 Example: byte a = 10

3. short Data Type:


 The short data type is a 16-bit signed integer. That is 2 byte.
 Its value-range lies between -32,768 to 32,767 (inclusive).
 Its default value is 0.
 Example: short s = 10000

4. int Data Type:


 The int data type is a 32-bit signed integer. That is 4 byte.
 Its value-range lies between (-2^31) to (2^31 -1).
 Its default value is 0.
 Example: int a = 100000;

5. long Data Type :


 The long data type is a 64 bit signed integer. That is 8 byte.
 The value-range lies between (-2^63) to (2^63 -1).
 Its default value is 0.
 Example: long a=123455334453;

6. float Data Type :


 The float data type is a 32-bit floating point. That is 4 byte
 Its value range is 1.4 e-45 to 3.4e+38
 Its default value is 0.0F.
 Example: float f1 = 234.5f;

7. double Data Type:


 The double data type is a 64-bit floating point. That is 8 byte.
 Its value range is 4.9e-324 to 1.8e+308
 Its default value is 0.0.
 Example: double d1 = 12.3l;

8. char Data Type:


 The char data type is a single 16-bit Unicode character. That is 2 byte.
 The char data type is used to store characters.
 Example: char letterA = 'A';

Non-Primitive (Reference) Data Types:


Non-primitive data types include Classes, Arrays, and Interfaces. They store references to the objects,
meaning they don't hold the actual data value but rather the memory address where the data is stored.

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;

public void displayDefaultValues()


{
System.out.printf("Default Integer: %d%n", myInt);
System.out.printf("Default Float: %.2f%n", myFloat);
System.out.printf("Default Double: %.2f%n", myDouble);
System.out.printf("Default Character: '%c'%n",myChar);
System.out.printf("Default Boolean: %b%n", myBoolean);
System.out.printf("Default Long: %d%n", myLong);
System.out.printf("Default Byte: %d%n", myByte);
System.out.printf("Default Short: %d%n", myShort);
}

public static void main(String[] args)


{
DefaultValuesExample example = new DefaultValuesExample();
example.displayDefaultValues();
}
}
Output:
Default Integer: 0
Default Float: 0.00
Default Double: 0.00
Default Character:
Default Boolean: false
Default Long: 0
Default Byte: 0
Default Short: 0

11. List and explain the Tokens in the Java language.

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

 Description: Java uses a few special symbols with unique functions.


 Examples:
o @ - Used for annotations, e.g., @Override.
o # - Not commonly used directly in Java code, but often seen in documentation.
o $ - Used in identifiers, especially in dynamically generated class names.

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.

There are two types of type casting. They are,


1. Implicit Type casting
2. Explicit Type casting

Implicit Type casting or Widening Type Casting:


 Converting a lower data type into a higher one is called widening type casting. It is also known as
implicit conversion or casting down.
 Implicit type casting is done automatically by a compiler when we assign a value to the variable.
 It is safe because there is no chance to lose data.
 byte -> short -> char -> int -> long -> float -> double
 int a=10; double b; b=a;
 Here a is integer and b is double variables.
 Integer value is automatically converted into double by the compiler.

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

Explicit Type casting OR Narrowing Type Casting:


 Converting a higher data type into a lower one is called narrowing type casting.
 It is also known as explicit conversion or casting up.
 It is done manually by the programmer. In this conversion, there is loss of data.
 double -> float -> long -> int -> char -> short -> byte
 type variable = (new_type) variable; double d = 6.865;
 int a = (int) d;

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.

Java variable naming rules:


 All variable should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
 Variable can never used special character like +,-,&,*.
 Space are not allowed in variable names.
 A keyword cannot be used as an variable name.
 Most importantly, variable are case sensitive. Such as ADD or add both are different.
 After the first character, variable can have any combination of characters.

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."

14. Demonstrate the operator precedence using a Java program.

Precedence and Associativity of Operators:


 Operator precedence determines the order in which the operators in an expression are evaluated.
 Precedence and associativity are two features of Java operators.
 When there are two or more operators in an expression, the operator with the highest priority will be
executed first.
 Associativity specify the direction that is left to right or right to left.

15. Describe how command-line arguments are passed to a java program and accessed within the
program.

Command –line arguments:


 The java command-line argument is an argument i.e. passed at the time of running the java program.
 The arguments passed from the console can be received in the java program and it can be used as an
input.
 When a Java application is invoked, the runtime system passes the command line arguments to the
application's main method through an array of strings.
 It must be noted that the number of arguments in an array. To ensure this, we can make use of the
length property of the array.
 The first argument is stored at args[0]
 The second argument is stored at args[1] and so on…..

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);
}
}

public class Main


{
public static void main(String[] args)
{
Example.displayNumber();
Example.number = 10;
Example.displayNumber();
}
}
Output:
The value of number is: 5
The value of number is: 10

17. Discuss the use of escape sequences in java strings for representing special characters.

Escape Sequence Characters:


A character preceded by a backslash (\) is an escape sequence and has a special meaning to the compiler.
The following table shows the Java escape sequences.

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.

Rules to define java identifiers:


 Identifier must start with a letter, a currency character ($), or a connecting character such as
underscore (_).
 Identifier cannot start with a number.
 Uppercase and lowercase letters are distinct.
 Total, TOTAL and total are different.
 They can be of any length.
 It should not be a keyword.
 Spaces are not allowed.

Conventions for identifier names:


 Names of all public methods and instance variables start with lowercase, for more than one word
second word’s first character shold be capital.
Ex:- total, display(), totalMarks, netSalary, getData()
 All classes and interfaces should start with capital letter, for more then one word the second word’s
first character should be capital.
Ex:- Student, HelloJava
 Constant variables should be in capital letters and for more than one word underscore is used.
Ex:- MAX, TOTAL_VALUE
 Package name should be in lowercase only.
Ex:- mypack

19. List and explain the formatted input and output statements.

Formatted Output with printf()


 To format and display the output, printf() method is available in PrintStream class.
 This method works similar to printf() function in C.
 Note: printf() is also available from J2SE 5.0 or later.
 The following format characters can be used in printf():
 The syntax of the method printf () method is as follows
 System.out.printf("Formatting string" variables separated by comma);
 %s – String
 %c – char
 %d – decimal integer
 %f – float number
 %o – octal number
 %b, %B – Boolean value
 %x, %X – hexadecimal value
 %e, %E – number scientific notation
 %n – new line character
Example:
class PrintfDemo
{
public static void main(String[] args)
{
String s="sai";
int n=65;
float f=15.45f;
System.out.printf(" String =%s %n number=%d %n Float=%f",s,n,f);
}
}
Output:
String = sai
Number= 65
Float=15.45

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.

Feature C++ Java

Platform-
C++ is platform-dependent. Java is platform-independent.
independent

Java is mainly used for application


C++ is mainly used for programming. It is widely used in Windows-
Mainly used for
system programming. based, web-based, enterprise, and mobile
applications.

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.

Operator C++ supports operator


Java doesn't support operator overloading.
Overloading overloading.

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.

C++ supports structures and


Structure and Union Java doesn't support structures and unions.
unions.

C++ doesn't have built-in


support for threads. It relies
Thread Support Java has built-in thread support.
on third-party libraries for
thread support.

C++ supports virtual


Java has no virtual keyword. We can override
keyword so that we can
Virtual Keyword all non-static methods by default. In other
decide whether or not to
words, non-static methods are virtual by default.
override a function.

Java always uses a single inheritance tree


C++ always creates a new because all classes are the child of the Object
Inheritance Tree
inheritance tree. class in Java. The Object class is the root of
the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object-oriented C++ is an object-oriented Java is also an object-oriented language.


language. However, in the C However, everything (except fundamental
language, a single root types) is an object in Java. It is a single root
hierarchy is not possible. hierarchy as everything gets derived from
java.lang.Object.

You might also like