0% found this document useful (0 votes)
7 views14 pages

Ca notes

The document provides an overview of Java programming concepts, including tokens, keywords, identifiers, literals, data types, operators, and packages. It explains the characteristics of various data types, the importance of documentation, and the use of comments in Java code. Additionally, it discusses Java Class Libraries, operator precedence, and the structure of Java packages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views14 pages

Ca notes

The document provides an overview of Java programming concepts, including tokens, keywords, identifiers, literals, data types, operators, and packages. It explains the characteristics of various data types, the importance of documentation, and the use of comments in Java code. Additionally, it discusses Java Class Libraries, operator precedence, and the structure of Java packages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Q. 1 What is token? Give example of 2 types of token?

Ans. The smallest individual entity used in the program is known as java token. When we
submit a Java program to the Java compiler, the compiler parses the text and extracts
individual tokens
Types of token:
1. Keyword
2. Identifiers
3. Literals
4. Operators
5. Separator (or Punctuators)
Q. 2 What are keywords? Give an example.
Ans. Keywords are reserved words which convey special meaning to the compiler. They are
written in small letters. They cannot be used as names for identifiers, class or methods. E.g.:
class, void
abstract double int switch char for
assert else interface synchronized class goto
boolean extends long this const if
break false native throw continue implements
byte final new transient default import
case finally package true do instanceof
catch float private try void volatile
Q. 3 What are identifiers in Java?
Ans. Identifiers are tokens that represent names. These names can be assigned to
variables, methods, and classes to uniquely identify them to the compiler. Variables are
declared with a data type. E.g. n, x, val3, _age, $val etc.
A Java Identifier must have following characteristics
 Can consist of uppercase, lowercase, digits, $ sign and underscore (_) character
(NO SPACE)
 Begins with letter, $, or _ (NO NUMBER)
 Is case sensitive
 Cannot be a keyword
 Can be of any length
Q. 4 What are literals in Java?
Ans. Literals or constants are tokens which do not change its value during the execution of
the program.
There are 5 types of Literals
 Integer literal
E.g int WEEK = 7, color = 0x24, code = 0b0100, v = 10L;
 Floating Point literal – It is of type double and float
E.g. double d = 23.2, float PI = 3.14F;
 Boolean literal – It has 2 values true and false
E.g. boolean STATE = true;
 Character literal – It is always enclosed in single quotes
E.g char ANS = ‘Y’, A = 065, ch = ‘\n’;
 String literal – It is always enclosed in double quotes
E.g String CAPITAL = “New Delhi”;
Q. 5 What is difference between float literal and double literal?
Ans.
Float Literal double Literal
The float literal is a single-precision 32-bit (4 bytes) floating point The double literal is a double-precision 64-bit (8 b
literal that can store any number along with fractional part literal that can store any number along with fracti
It can handle 7 decimal places. It can handle16 decimal places.
Q. 6 What do you mean by Punctuators? Give example?
Ans. Punctuators are also called as separators. They are specific symbols or tokens used to
indicate how group of code is divided and arranged.
Examples:
[ ] (used for creating array),
{} (used to make compound statement body),
() (used to perform arithmetic operations, used to enclose arguments of the function,
for type casting),
; (semicolon- used as statement terminator),
, (comma- used to separate list of variables),
. (dot or decimal- used make fraction value, include package, referencing object).
Q. 7 What is the difference between Static and Dynamic Initialization?
Ans STATIC Initialization: Variable is initialized during its declaration with defined constant.
E.g. int i = 10;
DYNAMIC Initialization: Variable is initialized at run time, i.e. during execution.
E.g. i = a + b;
Q. 8 What is the final keyword used for?
Ans. The final keyword converts the variable into constant whose value cannot be changed
at any stage in the program.
It is used when we need that the value of a variable should not change. Like value of
constants , Pi etc.
Example:
int x= 10;
final int y = 20;
x= x +7;
y= y+7; // it gives compilation error message-
// “cannot assign a value to final variable y”
Q. 9 How much space do the following take – bit, terabyte, nibble, kilobyte?
Ans.
Name Size
Bit 1 bit
Nibble 4 bits
Byte 8 bits
Kilobyte 1,024 bytes
Megabyte 1,024 kilobytes
Gigabyte 1,024 megabytes
Terabyte 1,024 gigabytes
Petabyte 1,024 terabytes
Exabyte 1,024 petabytes
Zettabyte 1,024 exabytes
Yottabyte 1,024 zettabytes
Q. 10 What is Data type?
Ans. Data type refers to the type of data that can be stored in a variable. Java has two types
Primitive and Reference Data Types.
Q. 11 What is Primitive Data Type?
Ans. Primitive Data Types are Data types which are built into Java language. E.g. int,char
etc. Java has following data type
Q. 12 What is reference data type? Give 2 examples of reference data types?
Ans. The data type formed with the help of primitive data type are known as reference data
type.
Example: Class, Interface and Array.
Q. 13 Why is Java called as strongly typed language?
Ans. Java is called as strongly typed language as variables can ONLY take value that
matches the variable’s declared type. The compiler ensures that the program does not try to
assign data of the wrong type to the variable.
For e.g. in statement below, you cannot assign double to an int variable. It will give an error.
int val1 = 12.6; // Error
Q. 14 What is Type casting? What are 2 types of casting available in Java?
Ans. To convert one predefined data type to another data type is known as Type Conversion
or Type Casting.
There are two type of type casting:
1. Explicit Type Casting
2. Implicit Type Casting
Q. 15 What is Explicit and Implicit Type casting?
Ans.
Implicit Typecasting :
When a data type of lower size (occupying less memory) is assigned to a data type of
higher size, it is done implicitly by the JVM. The lower size is widened to higher size. This is
called as Implicit Typecasting and is also named as automatic type conversion.
Implicit type casting occurs if you assign any of these data types to higher data types
byte –> short –> int –> long –> float –> double
e.g
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.
Note A boolean value cannot be assigned to any other data type.
Explicit Typecasting :
A data type of higher size (occupying more memory) cannot be assigned to a data type of
lower size. This is not done implicitly by the JVM and requires explicit casting; a casting
operation to be performed by the programmer. The higher size is narrowed to lower size.
A narrowing primitive conversion may lose information about the overall magnitude of a
numeric value and may also lose precision and range.
e.g.
double x = 10.5; // 8 bytes
int y = x; // 4 bytes ; raises compilation error
int y = (int)x; // ok. Explicit Typecasting
Q. 1 What are operators?
Ans. Operators are special symbols that perform specific operations on Operands
e.g. +, – , <,
Q. 2 What are three classifications of operators?
Ans. Java operators can be classified as unary, binary, or ternary—meaning taking one,
two, or three arguments, respectively.
 Unary: Increment ++, negation –
 Binary: a + b, num = c
 Ternary: Conditional Operator ?
Q.3 What is assignment operator?
Ans. Assignment operators is used to assign a value to a variable
Syntax: < variable > = < expression >
e.g.
double time = 2.10d;
char c = ‘c’;
int counter = 1;
String name = “Nisha”;
boolean rs = true;
counter = 5; // previous value is overwritten
Q. 4 What are arithmetic operators?
Ans. Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. There are 8 types of Arithmetic operators
 Plus (+), Minus (-), Multiply (*), Divide (/)
 Modulus/ Reminder (%)
 Increment (++), Decrements (–)
Assuming A is 10 and B is 20
Operator Description Ex
+ Addition – Adds values on either side of the operator A
– Subtraction – Subtracts right hand operand from left hand operand A
* Multiplication – Multiplies values on either side of the operator A
/ Division – Divides left hand operand by right hand operand B
% Modulus – Divides left hand operand by right hand operand and returns remainder B
++ Increment – Increase the value of operand by 1 B+
— Decrement – Decrease the value of operand by 1 B–
Q. 5 What are relational operators?
Ans. Relational operators are used to compare two operands. It returns only Boolean
value either true or false.
E.g <, >,<=, >=, ==, !=
Operator Description
== Checks if the value of two operands are equal or not, if yes then condition becomes true.

!= Checks if the value of two operands are equal or not, if values are not
equal then condition becomes true.
> Checks if the value of left operand is greater than the value of right operand,
if yes then condition becomes true.

< Checks if the value of left operand is less than the value of right operand,
if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condi
Operator Description
becomes true.

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then conditio
true.
Q.6 What are logical operators?
Ans. Logical Operators are used to combine one or more relational expressions. It
returns true or false value. It operates only on boolean values. E.g a = (b < c) && (d<e)
Operato
Description
r
&& Logical AND operator. If both the operands are non zero then then condition becomes true.

|| Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
! Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then
Logical NOT operator will make false.
Q. 7 What is ternary operator in Java?
Ans. Conditional or ternary is the only three argument operator in Java. This operator
consists of three operands and is used to evaluate boolean expressions.
Syntax: variable x = (expression) ? value if true : value if false
E.g. b = (a == 1) ? 20: 30;
Q. 8 What is operator precedence?
Ans. The order in which operators are applied is known as precedence. Operators with
a higher precedence are applied before operators with a lower precedence.

Q. 1 What is JCL?
Ans. Java Class Library (JCL) are dynamically loadable libraries that Java
applications can call at run time. Some examples of JCL are java.lang,
java.util, java.math, java.awt. etc.
Q. 2 What are packages? Why do we need packages?
Ans. Java contains an extensive library of pre-written classes (JCL) you can
use in your programs. These classes are divided into groups called packages.
A Package is a collection of related classes, providing access protection and
name place management.
Java uses packages because
 It makes search and re-using packages and classes easier.
 It prevents naming conflicts. You can have a class with same name
in two different package.
 Provides controlled access as you can specify protected and default
access specifier for methods which work within a package
Q. 3 Which keyword is used to include packages in your source code?
Ans. import keyword is used to import built-in and user-defined packages
into your java source file so that your class can refer to a class that is in
another package by directly using its name.
Q. 4 Which package is automatically imported by Java?
Ans. “ java.lang“ Package is automatically imported by Java.
Q. 5 Name the package that contains – 1) BufferedReader 2) Scanner
3) Math?
Ans. 1) BufferedReader: java.io
2) Scanner: java.util
3) Math: java.lang
Q. 6 Which class is at root of Java Class Hierarchy?
Ans.
i) Object class is at the root class hierarchy and Class, instances of which
represent classes at runtime.
ii) They are part of java.lang package.
Q. 7 What is JAR?
Ans.
 A java library is deployed in a jar file format.
 JAR or Java Archive is like a zipped file which contains many java
classes and its associated resources such as images, text etc. into
one file to distribute as libraries
Java Math Class :
The java.lang.Math class contains various methods for performing basic
numeric operations such as the logarithm, cube root, and trigonometric
functions etc. The various java math methods are as follows:

Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
Math.pow() It returns the value of first argument raised to the power to second argument.
Math.ceil() It is used to find the smallest integer value that is greater than or equal to
the argument or mathematical integer.
Math.floor() It is used to find the largest integer value which is less than or equal
to the argument and is equal to the mathematical integer of a double value.
Math.rando It returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.
m()
Math.rint() It returns the double value that is closest to the given argument and equal to mathematic
Math.log() It returns the natural logarithm of a double value.
Math.exp() It returns E raised to the power of a double value, where E is Euler’s number and it
is approximately equal to 2.71828.
Math.sin() It is used to return the trigonometric Sine value of a Given double value.
Math.cos() It is used to return the trigonometric Cosine value of a Given double value.
Method Description
Math.tan() It is used to return the trigonometric Tangent value of a Given double value.

Question 1

What is a java package? Give an example.

Answer

A package is a named collection of Java classes that are grouped on the basis of their
functionality. For example, java.util.

Question 2

Explain the use of import statement with an example.

Answer

import statement is used to import built-in and user-defined packages and classes into
our Java program. For example, we can import all the classes present in the java.util
package into our program using the below statement:

import java.util.*;

Question 3

Explain the statement, "a well-documented code is as important as the correctly


working code".

Answer

Writing fully commented code is a good programming style. The primary purpose of
comments is to document the code so that even a layman can understand the purpose
of the written code. Hence, a well-documented code is as important as the correctly
working code.

Question 4

How can you write single line comments in Java?

Answer

Single line comments in Java can be written in the below two ways:

1. Using Single line comments style — Single line comment begin with a
double slash (//) and continues till the end of the line. For example:

// Single line comment example

2. Using Multi line comments style — In this style, comments start with the
initiating slash-asterisk (/*) and ends with the terminating asterisk-slash(*/). For
example:

/* Single line comment using multi line comment style */


Question 5

Explain data input technique in a program using the Scanner class.

Answer

The data entered by the user through the keyboard is provided to our Java program
with the help of standard input stream that is specified as System.in in the program.
We connect our Scanner class to this stream while creating its object. The input
received by Scanner class is broken into tokens using a delimiter pattern. The default
delimiter is whitespace. Scanner class provides various next methods to read these
tokens from the stream. The different next methods provided by Scanner class are
next(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), nextLine(),
next().charAt(0).

Question 6

Distinguish between the following:

i. next() and nextLine()

Answer

next() nextLine()

It reads the
input only
till the next
complete
token until It reads the input till the end of line so it can read a full sentence including spaces.
the
delimiter is
encountere
d.

It places the
cursor in
the same
It places the cursor in the next line after reading the input.
line after
reading the
input.

ii. next() and next().charAt(0)

Answer

next() next().charAt(0)

It reads the It reads the complete token and then the first character is returned using the charAt
input only
till the next
complete
token until
the
next() next().charAt(0)

delimiter is
encountere
d.

It returns
the read
data as a It returns the read data as a char value.
String
value.

iii. next() and hasNext()

Answer

next() hasNext()

It reads the input till the next


complete token until the It checks if the Scanner has another token in its input.
delimiter is encountered.

It returns a String value. It returns a boolean value.

iv. hasNext() and hasNextLine()

Answer

hasNext
hasNextLine()
()

Returns
true if
the
Scanner
object Returns true if there is another line in the input of the Scanner object.
has
another
token in
its input.

Question 7

What are delimiters? Which is the default delimiter used in the Scanner class?

Answer

A delimiter is a sequence of one or more characters that separates two tokens. The
default delimiter is a whitespace.
Question 8

What are errors in a program?

Answer

Errors are mistakes in a program that prevents it from its normal working. They are
often referred to as bugs. Errors are classified into three categories — Syntax Errors,
Runtime Errors and Logical Errors.

Question 9

Explain the following terms, giving an example of each.

i. Syntax error

Answer

Syntax Errors are the errors that occur when we violate the rules of writing the
statements of the programming language. These errors are reported by the compiler
and they prevent the program from executing. For example, the following statement
will give an error as we missed terminating it with a semicolon:

int sum
ii. Runtime error

Answer

Errors that occur during the execution of the program primarily due to the state of the
program which can only be resolved at runtime are called Run Time errors.
Consider the below example:

import java.util.Scanner;

class RunTimeError
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = in.nextInt();
int result = 100 / n;
System.out.println("Result = " + result);
}
}
This program will work fine for all non-zero values of n entered by the user. When the
user enters zero, a run-time error will occur as the program is trying to perform an
illegal mathematical operation of division by 0. When we are compiling the program,
we cannot say if division by 0 error will occur or not. It entirely depends on the state of
the program at run-time.

iii. Logical error

Answer

When a program compiles and runs without errors but produces an incorrect result, this
type of error is known as logical error. It is caused by a mistake in the program logic
which is often due to human error. Logical errors are not caught by the compiler.
Consider the below example for finding the perimeter of a rectangle with length 2 and
breadth 4:

class RectanglePerimeter
{
public static void main(String args[]) {
int l = 2, b = 4;
double perimeter = 2 * (l * b); //This line has a logical
error
System.out.println("Perimeter = " + perimeter);
}
}

Output

Perimeter = 16
The program gives an incorrect perimeter value of 16 as the output due to a logical
error. The correct perimeter is 12. We have written the formula of calculating perimeter
incorrectly in the line double perimeter = 2 * (l * b);. The correct line should
be double perimeter = 2 * (l + b);.

Question 10

A program has compiled successfully without any errors. Does this mean the program
is error free? Explain.

Answer

Successful compilation of the program only ensures that there are no syntax errors.
Runtime and logical errors can still be there in the program so we cannot say that the
program is error free. Only after comprehensive testing of the program, we can say
that the program is error free.

Question 11

Write a program in Java that uses 'input using initialisation' to calculate the Simple
Interest and the Total Amount with the given values:

i. Principle Amount = Rs. 20000


ii. Rate = 8.9%
iii. Time = 3 years

Answer

public class KboatInterest


{
public static void main(String args[]) {
int p = 20000;
double r = 8.9;
int t = 3;
double si = p * r * t / 100.0;
double amt = p + si;
System.out.println("Simple Interest = " + si);
System.out.println("Total Amount = " + amt);
}
}
Output

Question 12

Write a program in Java that accepts the seconds as input and converts them into the
corresponding number of hours, minutes and seconds. A sample output is shown below:

Enter Total Seconds:


5000
1 Hour(s) 23 Minute(s) 20 Second(s)

Answer

import java.util.Scanner;

public class KboatTimeConvert


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter time in seconds: ");
long secs = in.nextLong();
long hrs = secs / 3600;
secs %= 3600;
long mins = secs / 60;
secs %= 60;
System.out.println(hrs + " Hour(s) " + mins
+ " Minute(s) " + secs + " Second(s)");
in.close();
}
}

Output
Question 13

Write a program in java to input the temperature in Fahrenheit, convert it into Celsius
and display the value in the Terminal window. A sample output is displayed below:

Enter temperature in Fahrenheit


176
176.0 degree Fahrenheit = 80.0 degree Celsius
Answer

import java.util.Scanner;

public class KboatTemperature


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter temperature in Fahrenheit: ");
double f = in.nextDouble();
double c = (f - 32) * 5.0 / 9.0;
System.out.println(f + " degree Fahrenheit = " + c + " degree
Celsius");
}
}

Output

You might also like