JAVA Notes_final
JAVA Notes_final
Year 2021-2022
CHETNA LALWANI
INDEX
TOPICS PAGES
Introduction to Java 3
Object Oriented Programming 4
Concepts
Encapsulation And Inheritance 7
Operators and Expressions in Java 8
Input Output Stream 13
Mathematical Functions 13
Decision Making Statements 15
Iteration through Loops 17
Constructor 20
Functions 23
String 27
Array 30
Exception Handling 34
Scanner Class 35
Keywords 36
Differences 37
2
Introduction To Java
Q7. Why is Java known as Platform Independent Language? OR What is WORA (Write once
run anywhere)
A7.A Java program can be compiled once into Java Byte code which is same across all
platforms. The compiled program can then be run on any computer that has an interpreter for the
Java Virtual Machine. It is therefore considered ‘Platform Independent’.
Q13. Write the file extensions of source code & intermediate code(byte code)
A13. Source code: .java
Byte code: .class
Polymorphism - It is the ability of methods to take more than one form. Several method names
can be same, but manipulate different types of data.
Benefits- Function Overloading and Overriding
Inheritance - It is the process by which objects of one class acquire the properties of objects of
another class.
Benefits - It helps in code reusability
Q7. What is the difference between Procedure Oriented Programming and Object Oriented
programming ?
A7.
Process Oriented Object Oriented
The program revolves around the code. The program revolves around the data.
It follows top-to-bottom approach. It follows bottom-to-top Approach.
Eg: Qbasic , C Eg: C++, JAVA
6
Encapsulation And Inheritance
1. Encapsulation promotes data hiding. Explain
A1. Encapsulation prevents data to be accessed directly. The code and the data can only be
accessed through an interface. This is called Information Hiding. Thus encapsulation promotes
data hiding.
Q2.Differentiate ASCII&UNICODE.
A2.
ASCII UNICODE
It stands for American Standard code for It stands for Universal code.
Information Interchange.
It has 0 to 256 characters. It has 0 to 65536 characters.
Q4.What is a keyword?
A4.Keywords are reserved words that convey special meaning to the compiler. They cannot be
used as identifiers. eg. float, void, while, else, break etc
Q9.What is the precedence of operators? Name the operators with highest and lowest
precedence?
A9.The order in which the operands are operated by operators in an expression is known as
precedence of operators. Operators with same precedence are executed from left to right.
Operator with highest precedence--> ()
Operator with lowest precedence--> =
9
Q10.Explain with e.g. unary, binary and ternary operators?
A10. An operator that requires one operand is called an unary operator. eg. a++
An operator that requires two operands is called a binary operator. eg. a+b
An operator that requires three operands is called a ternary operator.eg. x=a>b?a:b;
Q14.Name all the primitive datatypes, their sizes in bytes & default values.
Name Size Default value
byte 1 0
short 2 0
int 4 0
long 8 0L
float 4 0.0f/0.0F
double 8 0.0d/0.0D
boolean 1 false
char 2 /u0000
10
A16.When a variable is declared using final keyword it becomes a constant i.e. its value cannot
be changed during the execution of the program. eg: final double pi=3.14
Q20. Define type conversions. Name the types of type conversions. Explain them.
A20. The process of converting one predefined type into another is called type conversion or
type casting. There are 2 types of conversions:
a) Implicit conversion - Conversion of one primitive datatype to another by the compiler is
known as implicit conversion. Destination type is larger than the source type. It is also known
as type promotion or coercion.
E.g. : int i =5 ;
char c = 'a';//a 97ASCII value
int sum=i+c; //sum=5+97=102
b) Explicit conversion - Conversion of one primitive datatype to another forcefully by the
programmer is known as explicit conversion. Source type is greater than the destination type. It
is also known as type casting.
E.g. : int x =5, y=10;
System.out.println( (float (x+y))/2); //7.5 is the answer
Typecast operator is ' ( ) '.
11
A21. Narrowing primitive conversion converts from larger data type to a smaller data type ,
thereby losing data during conversion . Narrowing primitive conversion can throw run time or
compile time exception errors.
12
Truth table for AND Truth table for OR
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0
0 1 1
1 0 1
1 1 1
INPUT/OUTPUT STREAM
Q1.Name the input/output streams used in java.
A1.System.in: The input stream is connected to the keyboard by the System class.
System.out: refers to the standard output stream.
System.err: refers to the output stream for error messages.
Q2. Write a java statement to input/read the following from the user using the keyboard.
i) Character char ch=(char)br.read();
ii)String String str=br.readLine();
Q4.What is a stream?
A4. A stream is an abstraction which either sends or receives information.
Q5. Name the three classes that play with character data.
13
A5. i)Character ii)String iii)StringBuffer
MATHEMATICAL FUNCTIONS
The Math class is defined in the java.lang package. The methods in the Math class are static
methods. The general syntax is: Math.functionname();
Q)What is symbolic constant? Name the symbolic constants of the Math class.
14
A) A symbolic constant is a variable whose value does not change during the entire lifetime of
the program. The symbolic constants of the math class are :
Math.e represents e, the base of the natural logarithm which is approximately 2.71828
Math.pi represents the ratio of the circumference of a circle to its diameter as 22/7 or 3.14.
Q3. What are the three constructs that govern statement flow?
A3. The three constructs that governs statement flow are: Sequence, Selection and Iteration
constructs.
Q4. What is a selection/conditional statement? Which selection statement does Java provides?
A4. A selection statement is the one that is used to decide which statement should be executed
next. This decision is based upon a test condition. The selection statements provided by Java are:
if-else and switch.
Q7. Write one advantage and one disadvantage of using ?: in place of an if.
A7. Advantage: It leads to a more compact program.
Disadvantage: Nested becomes difficult to understand or manage.
Q16. Discuss when does an if statement prove more advantageous then switch statement.
A16. In the following case if statement proves to be more advantage over switch statement:
(i) when a range of values need to be tested for.
(ii) When relation between multiple variables needs to be tested.
(iii) When multiple conditions need to be tested.
(iv) When expressions having a data type other then integer or character need to be tested.
Q17. Explain, with the help of an example, the purpose of default in a switch statement.
A17. In switch if none of the cases matches the switch expression, then the default statement is
executed. The default statement is optional and is the last statement in switch. If no case is true
and default statement is not present, no further action is taken.
switch(n)
{
case 1: System.out.println(“Sunday”); break;
case 2: System.out.println(“Monday”); break;
case 3: System.out.println(“Tuesday”); break;
default : System.out.println(“Invalid Input”);
}
Q2. What is the difference between entry controlled or exit controlled loops? OR
What is the difference between while and do-while loops.
A2. Entry controlled loop : In this construct the test expression is evaluated first and then the
statements are executed. The loop is not executed if the condition is false for the first time .
eg. for, while loop
Exit controlled loop: In this construct the test expression is evaluated after the execution of the
statements. The loop executes at least once even if the condition is false for the first time.
eg: do-while loop.
18
Syntax:
Initialization;
while(condition)
{statements;
}
Q7. Explain do while loop.
A7.It is an exit controlled loop. It is used when the number of iterations are unknown. It first
executes the statements and then checks the conditions. So it executes the loop at least once.
Syntax:
initialize;
do{
Statements;
}while(condition);
Q9. Give differences and similarities between while and for, while and do-while
While loop For loop
Number of iterations are unknown Number of iterations are known
All the expressions are written on different All the expressions are written on the same
lines. line.
Similarity : Both are entry controlled loops
It first checks the condition and then executes It first executes the statements and then checks
the statements the condition
It is entry controlled loop It is exit controlled loop
It will not execute if the condition is false. It is executed at least once even if the condition
is false.
Similarity : Both the loops are used when the number of iterations are not known.
Output: 1 2 4 5
CONSTRUCTORS
Q1.What is constructor? Why do we need a constructor as a class member?
A1. A class is a combination of member variables and methods. The member variables are
initialized by a constructor. A constructor is a member function that is automatically invoked,
when the object is created of that class. It has the same name as that of the class name and has no
return type. Constructor is needed as a member of the class to initialize objects upon creation i.e.
to initialize data members of the class.
20
Q3. Explain default constructor or non-parameterized constructor.
A3. The constructor that accepts no parameters to initialize the data members of the class is
called the default constructor. If we do not explicitly define a constructor for a class., then java
creates a default constructor for the class. Example:
class ant
{
int x,y;
public ant()
{ x=0;y=0;}
public static void main()
{ant nc=new ant();}
}}
Q5. Give a syntax/example of constructor overloading. Define a class, which accept roll number
and marks of a student. Write constructor for the class, which accepts parameter to initialize the
data member. Also take care of the case where the student has not appeared for the test where
just the roll number is passed as argument.
A5. class student
{
int roll;
float marks;
student(int r, float m) // constructor with two argument.
{
roll=r;
marks=m;
}
student (int r) // constructor with one argument
{
roll=r;
marks=0;
}
student() // default constructor
21
{
roll=0;
marks=0;
}
}
Q8. Enter any two variables through constructor parameters and write a program to swap and
print the values.
class swap
{
int a,b;
swap(int x,int y)
{
a=x;
b=y;
}
public void main(String args[])
{
int t=a;
a=b;
b=t;
System.out.println(“the value of a and b after swapping : “+a+” “+b);
}
}
FUNCTIONS
Q1. What is a Function? Q. Explain Functions/Methods definitions with syntax?
A1: Functions are the modules from which java programs are built. They exist inside a class.
23
A function must be defined before it is used anywhere in the program.
Access specifier Modifier return-type function-name (parameter list)
{
body of the function
}
[access specifier] can be Public, Protected or Private. [Modifier] can be one of final, native,
synchronize, transient, volatile. Return-type specifies the type of value that the return statement
of the function returns. It may be any valid Java data type. Parameter list is comma separated list
of variables of a function.
Function signature basically refers to the number and types of the arguments; it is the part of
the prototype.
24
Q9. What is the use of static in main() methods?
A9. (i) They can only call other static methods. (ii) They can only access static data. (iii) They
cannot refer to this or super in any way.
In call by reference, data types like objects and arrays are passed by call by reference. Any
changes made in the formal parameter is reflected in the actual parameter.
Impure Function: These functions change the state of the arguments they have received. Impure
functions are also called Mutator methods
For example following code overloads a function area to computer areas of circle, rectangle and
triangle.
float area (float radius) //circle
{
return (3.14 * radius * radius);
}
float area (float length, float breadth) //rectangle
{
return (length*breadth);
}
float area (float side1, float side2, float side3) //area of triangle
{
float s = (side1 + side2 + side3)/2;
float ar = Math.sqrt(s * (s- side1)*(s-side2) *(s-side3));
25
return (ar);
}
Q18. Write the function prototype for the function sum that takes an integer argument x as its
argument and returns a value of float data type.
A18.public float sum(int x)
26
A19.When the function call in a program is decided during compilation it is known as early or
static binding. When the function call in a program is decided during the execution of the
program it is known as late or dynamic binding.
Q21.i)If a function contains many return statements, how many of them will be executed?
ii)Which OOP principle implements function overloading?
A21.i)only one return statement will be executed.
ii) Polymorphism
STRINGS
Q1. Define String?
A1. A string is a sequence of characters written within double quotes. e.g. “Happy New Year”,
“Computer Application” etc.
Q4. Write down the purpose of the following string functions: toLowerCase(), toUpperCase(),
replace(), trim(), equals(),equalsIgnoreCase(), length(), charAt(), concat(), substring(), indexOf(),
lastIndexOf(), compareTo(), startsWith(), endsWith()
A4. The purpose and syntax of the following string functions are:
toLowerCase(): This function converts all the characters of the string in lower case.
eg: String n="AMITABH";
n=n.toLowerCase();
System.out.println(n); output : amitabh
toUpperCase (): This function converts all the characters of the string in upper case.
eg: String n="Amitabh";
n=n.toUpperCase();
27
System.out.println(n); output: AMITABH
replace (): This function replaces all the occurrence of a character with another one.
String n="DAD";
n=n.replace('D','G');
System.out.println(n); output: GAG
trim(): This function is used to remove all the white spaces at the beginning and end of string.
String n="AMIT ";
n=n.trim();
System.out.println(n);
equals(): This function is used to compare two string and returns true if equal else false.
String s1="AMIT";
String s2="amit";
System.out.print(s1.equals(s2)); output: false
equalsIgnoreCase():This function is used to compare two strings and returns true if the strings
are equal after ignoring cases and false if they are unequal.
String s1="AMIT";
String s2="amit";
System.out.print(s1.equals(s2)); output: true
length(): This function returns the number of characters present in the string.
String s="AMITABH";
System.out.print(s.length()); output: 7
substring(): This function returns the substring starting from the nth character of the string.
String s="AMITABH";
System.out.print(s.substring(3)); output:TABH
This function also returns the substring starting from the nth character up to the mth character
without including the mth character of the string.
String s=”AMITABH”;
System.out.print(s.substring(2,4)); output:IT
indexOf (char): This function returns the position of the first occurrence of a character in the
string.
String s="AMITABH";
28
System.out.print(s.indexOf(‘A’)); output:0
indexOf(char,int):This function also returns the position of the character from the nth position of
the string.
System.out.print(s.indexOf(‘A’,2)); output:4
lastIndexof(char):This function returns the position of last occurrence of given character in the
string.
String s="AMITABH";
System.out.print(s.lastIndexOf(‘A’)); output:4
compareTo(): This function returns negative if first string is less then second string, positive if
greater and zero if equal.
String s1="AMIT";
String s2="SUMIT";
System.out.print(s1.compareTo(s2));
startsWith(String): This function returns true if the string starts with specified parameter string.
String s1="SUM";
String s2="SUMIT";
System.out.print(s2.startsWith(s1)); output:true
endsWith(String): This function returns true if the string contains a suffix specified by parameter
string.
String s1="MIT";
String s2="SUMIT";
System.out.print(s2.endsWith(s1)); output:true
Q5. What is the difference between equals() and equalsIgnoreCase() string functions?
A5. Both the functions are used to compare strings, the difference being that equals ()
distinguishes between upper case and lower case version of a character, whereas
equalsIgnoreCase () carries out comparison ignoring the case of characters. Both the functions
return a boolean value.
29
Q7. Differentiate between toLowerCase () and toUpperCase () methods.
A7. The given two string method’s change the case of the current string. The toLowerCase ()
method change the current string object to its equivalent Lower Case, whereas toUpperCase ()
method change the current string object to its equivalent Upper Case.
Q8. What is the difference between the length () and capacity () string function.
A8. The function length () returns the number of character in a string.
capacity () returns the maximum number of characters that can be stored in a string object.
Character class provides various methods to manipulate the character class type
Method Description
static boolean isDigit(char ch) Returns true if ch is digit else returns false
static boolean isLetter(char ch) Returns true if ch is letter else returns false
static boolean isLetterOrDigit(char ch) Returns true if ch is letter or digit else returns
false
static boolean isLowerCase(char ch) Returns true if ch is in lowercase else returns
false
static boolean isUpperCase(char ch) Returns true if ch is in uppercase else returns
30
false
static boolean isSpace(char ch) Returns true if ch is a white space else returns
false
static boolean toLowerCase(char ch) Returns lowercase equivalent of ch
static boolean isUpperCase(char ch) Returns uppercase equivalent of ch
ARRAYS
Q1. What do you understand by Arrays? How you declare an Array?
A1. An Array is a collection of variables of the same data type that are referenced by a common
name. Array can be declared by the following statements: int n [] =new int [10];
1 2 3
4 5 6
7 8 9
Q9. Name the error which is caused when the specified position exceeds the last index of the
array.
A9. Error raised is ArrayIndexOutOfBoundsException.
Eg: int a [] = {2, 4, 8,10};
For (int i=0; i<=5; i++)//Index 5 is not available.
{…..}
32
Q13. Comment on the efficiency of linear search and Binary Search in relation to the number of
element in the list being searched?
A13. The Linear search compares the search item with each element of the array, one by one. If
the search item happens to be in the beginning of the array, the comparisons are low, however if
the element to be searched for is one of the last elements of the array, this search technique
proves the worst as so many comparisons take place.
The Binary search tries to locate the search item in minimum possible comparisons, provided the
array is sorted. This technique proves efficient in nearly all the cases.
Q19. Show the representation of the given array in memory after the second iteration of selection
sort 4 3 2 5 7 6 8
Ans. Using Selection sort
4 3 2 5 7 6 8
2 3 4 5 7 6 8
33
2 3 4 5 7 6 8
Q20. Determine the number of bytes required to store the following arrays:
A20. int a [23]
Ans. 23*4=92 bytes
B. char b [17]
Ans. 17*2=34 bytes.
Q21.What is a subscript?
A21. An integer that is used to identify a specific memory location whose value can vary from 0
to n-1 for an array of n elements.
EXCEPTION HANDLING
Q2. What is an exception? What is exception handling? What are the ways to handle an
exception?
A2. An exception is an event, which during the execution of the program, disrupts the normal
flow of the program’s instructions.eg: division by zero, exceeding the bounds of the array.
Exception handling is a programming language construct or computer hardware mechanism
designed to handle the occurrence of exceptions, special conditions that change the normal flow
of program execution.
There are 2 ways in which exceptions can be handled:
Using try , catch , finally blocks.
throws keyword
Q5. Explain try and catch and finally blocks with example.
A5. The try and catch block is used for exception handing. The try block contains the normal
code that is to be executed and in which exceptions may occur. The catch block
contains the code to be executed if an exception is thrown by the try block. There can be
multiple catch blocks for a single try block. The finally block contains the code that has to be
executed , irrespective, whether an exception has occurred or not.
Eg:
class Temp
{
public void main(int a ,int b)
{
try
{
System.out.println(“division”+a/b)’
}
catch(Exception e)
{
Sytem.out.println(“error occurred”+e);
}
finally
{
System.out.println(“finally block is executed “);
}
}
}
Exception will be thrown if the value of variable b is zero and it will be handled by catch block.
35
Compile time error Run time error
The errors occur due to incorrect syntax in the The errors occur during execution of the
program program
Inspite of the errors in the program, the The program cannot be executed.
program can be compiled.
Errors occur during compilation of the Errors occur only during run-time
program.
SCANNER
The Scanner class is defined in the java.util package. A Scanner class object has to be created
before using the class.
Scanner sc= new Scanner(System.in);
The Scanner class works on the principle of tokens. A token is a series of characters that ends
with a delimiter. The default delimiter is a whitespace. For each of the primitive datatypes, there
is a corresponding next() and hasNext() methods that return the next token. If a value cannot be
interpreted by the method, an InputMismatchException is thrown. The advantage of using
Scanner class is that it is able to read all primitive datatypes from System.in or from a file.
The default delimiter can be changed as follows:
sc.useDelimiter(\\s*,\\s*);
Method Returns
int nextInt() Returns the next token as an int.
long nextLong() Returns the next token as long.
double nextDouble() Returns the next token as double.
float nextFloat() Returns the next token as an float.
String next() Returns the next token as string till whitespace
String nextLine() Returns the rest of the current line as string,
excluding any line separator at the end.
void close() Closes the scanner
Method Returns
boolean hasNextInt() Returns true if the next token is an int.
boolean hasNextLong() Returns true if the next token is long.
boolean hasNextDouble() Returns true if the next token is double.
boolean hasNextFloat() Returns true if the next token is float.
boolean hasNext() Returns true if the next token has another token
in its input.
boolean hasNextLine() Returns true if the next token has another line
in its input.
36
Differentiate between Scanner and BufferedReader class.
Scanner class BufferedReader class
It has methods to take input directly in It takes input in string type and then converts
primitive types. them to primitive datatypes.
It is present in java.util package. It is present in java.io package
There's no method to take input in char type. It uses read() method to input character data.
KEYWORDS
DIFFERENCES
isUpperCase(char) toUpperCase(char)
It checks if passed argument is uppercase or It converts the passed argument to Uppercase.
not
37
It returns boolean value. It returns char value.
Eg: boolean z= Character.isUpperCase('z'); Eg: char X=Character.toUpperCase('a');
Z=false X='A'
read() readLine()
read() method can read only one byte of data. readLine() method can read more than
Reads data in int type Reads data in String type
Eg: char k=(char)br.read(); Eg: String str=br.readLine();
charAt(int) indexOf(char)
It receives an integer argument and returns the It receives a character argument and returns the
character at that position. position of the first occurrence of the given
character in the String.
Return type is char. Return type is int.
Eg: char k="hello".charAt(2); Eg: int p="hello".indexOf('l');
K='l' p=2
= ==
It is an assignment operator. It is a relational operator.
It assigns the right hand side value to left hand It checks if two values are equal or not and
side variable. returns true or false
Eg: int a=5; Eg: (6= =5) returns false
Math.rint() Math.round()
It truncates the decimal part of the number and It truncates the decimal part of the number and
returns the nearest value in double datatype. returns the nearest value in int type.
double x=Math.rint(15.5); int x=Math.round(15.5);
x=16.0 x=16
38