Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Computer Notess

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Notes on functions

Q1 What are methods?

Ans . Functions are the modules from where java programs are built. Function body is enclosed in curly braces and
any set of statements known as a block.and have Some declarative statements and executable statements. Methods
implements the behaviour of the objects.

Q2. What are the rules of Function Name: -

Function naming rules:

1) It should start with lower case alphabet.


2) It should be a legal identifier name. There are certain pre-defined methods in java.
double x = Math.sqrt (n)→Parameter passed

↓ ↓ ↓

value stored in class metod name

Q3. How many parts a function have?

A function has two main parts i.e a header and a body. The first line is the function header. It specifies the return type,
the function name and the parameter list of function. It is also known as function definition Public int get
price (int p, int q)

Function Body: -

Function body is enclosed in curly braces and any set of statements known as a block.

Q4 What are the advantages of function

. There are atleast three main reasons to use methods in the program:

1) To cope up with the complex program


2) To cope low level details
3) To reuse the portions of the codes
4)
Q5 Write the syntax of Function definition: -

Syntax :

[ access specifier] [ modifier] return type function name ( parameter list)

[public protected private] [final static] { void int float, etc} (function name parameter)

Q6 What is function prototype and function signature?

Function Prototype: - Function Prototype is the first line of function definition that tells the program about the type of
the value return by the function and the number and type of arguments.

Function signature: - Function signature refers to the number and types of argument. It is the part of function
prototype, function signature and return type makes function prototype.

Q7 What is access specifiers?

Public, private is a access specifiers, it specifies, the visibility attribute of the method.

Q8 What is function calling? Which type of function can be used in expression?


Accessing a function: - A function is called or invoked by providing the function name followed by the parameter
being sent enclosed in paranthesis.

Call Statement: - Function call statement must provide the argument values being sent and the number and type of
argument values must be the same as in prototype order of argument should be same.

Example: area(x,y)

Only those functions can be used in the expression that have a return value.

Q9 Explain return: -

Return causes the exit from the method. Return is followed by an expression or a variable or the value to be return to
the calling program.

Q10. What are actual and formal parameters?

Actual & Formal Parameters: - The parameters that appear in the function definition are called formal parameters.

Example: public int area (int l, int b) Parameter list are the list of values that are passed into the function.

Argument in function call statement are called actual parameters.

Example: area(x,y)

Function operates on those types of values.

Q11.Explain Pure and impure function?

Pure functions : - (Accessor)

The function which returns value and do not change the state of there parameters are called pure functions. They
return information to the caller about the state of an object.
A method that obtain information about an object state may also be classified as an accessor. The class string
provides many accessor method
Example: public int getdata (int price )
{ return price; }
Impure functions:-(mutators)
The function which may or may not returns value and change the state of the objects or parameters passed as
a parameters
Example: public int getdata (int price )
{ return( price+10); }

Q12. What is call by value method ?


A ns. In cal by value method thefunction creates a duplicate copy of the arguments passed to the function it copies
the value of an argument into the parameter of the function.
2. Any changes made to the parameter inside the function are not shown outside the function.
3. parameters inside the function donot affect the original arguments.
4. all primitive datatypes are passed by values.

Q13. What is call by reference method?


Ans. In call by reference function does not create any duplicate copy but reference is passed to the function ,the
parameter that receives it will refer to the same object as that reffered by the argument
2. Any changes which are made inside the function are shown outside the function
3. the changes made to the object in the function will change to the object passed.
4. All reference datatype ,object are passed.

Q14. What is function overloading?


Ans. When there are more than one function in a class with the same name and different parameter list is called or
function signature is called as function overloading. It implements polymorphism oops property.

Q15 What is garbagge collection feature of java.


Ans . This is an automatic system which deletes all those objects automatically which are not frequently used and
releases the memory occupied by them.

Q16 What is ‘this ‘ keyword?


Ans . ‘this’ keyword refers to the current object.
When there is 2 variable one is local and other is global then to refer to the global in the scope of local ‘this’ keyword
is used.

Q17. What is the temporary object ?


Ans A temporary object is also called as temporary instance is one that is in the memory as long as it is being used in
an expression and after that it is destroryed Temporary object are created by explicit call to a constructer.

Q18. What is finalise() method?


Ans. In java there is a method which is called just before an objects final destruction by garbage collector .it is esed to
ensure that the object terminates clearly

Q19 What is parameter list? Parameter list: - Parameter list are variables that receives the value of the argument
passed to the function when it is called.
Notes on Array

Q1. What is an array? What type of data type is it?

Ans. Array is a collection of same type of variables and are reffered by a common name and stored in a continiuos
location. Array is called as reference data type because object of the array is created.

Q2.How is an array stored in the memory?

Ans .Arrays are stored in contigious location. And the lowest address corresponds to the first element and highest to last
element.

Q3.What is a subscript? And what is subscipted variable

Ans . Asubscript is an integer no starting from 0 to the size of the array-1. It is used to represent the index number of the
array.. and a variable with which a subs cript is attached is called as subscripted variable

4 How do you differentiate ordinary variable from an array variable?

Ordinary variable contains only one value in the memory whereas array variable contains a number of values in the
memory.

1. Differntiate between One dimensional arrays and Double dimensional arrays?

Single Dimension Array Double Dimension Array

It has linear storage Storage is logically equivalent to a matrix


Total number of elements in the array
is Maximum index +1 Total number of elements in array is Row
Count * Column count

5 Determine the total bytes required to store a[17], a character array?

Total bytes required for storing the specified array = 2*17=34, if 17 is the number of elements.
6 What is the data type of elements of an array called?

The data type of the element of an array is called the base of the array

7 How are the individual elements in array addressed?

Individual elements of an array are addressed using the name of the array plus the subscripts 0,1, … n-1, where n is the
number of elements in the array.
8 What are out of bound subscripts?
The subscripts other than 0 to n-1 (including both) for an array having n elements are called as out of bound subscripts.
Reference to an out of bound subscript produces an out of bound exception.

9 What are searching? Mention two important searching techniques?


To search particular element in an array , searching technique is applied.
Two important searching techniques are Linear Searching and Binary Searching.
10 How linear seach techniques function?
In linear search, each element of the array is compared with the given item to be searched for one by one. It is also known
as sequential search.

11 What is Binary search?


In binary search, the item is searched in minimum possible comparisons. For binary search the array should be sorted. In
this technique, the item is searched for in smaller segment after every stage.

12 Differrentiate between Binary Search and Linear Search?

Linear Search Binary Search


Can work on both sorted and unsorted
arras. Work only on sorted arrays
Reads and compares each element of Work by dividing the array into two
the array one by one till a match is segments, out of which only one needs to be
found. searched.
Tends to become inefficient as size Is more efficient than linear search in case of
increases larger arrays
13.What are the two
conditions binary search ?
1. The array elements should be sorted
2. The sort order must be known and limits should be known.

14.What are the advantages and disadvantages of array?

1. Maintaining multiple related variables with same data type becomes


Simpler as single variable name is associated with all elements
In array.
2. Size of array can be set according to requirements of user
3. Code becomes efficient and manageable as loops can be used to
Carry out operations of the array
Disadvantage
1.Once the size of array is set, it cannot be altered without losing
Information, as new operator allocateds different set of bytes to
The array.
2. Insertion or deletion of the elements of array requires either
backward or forward shifting of data, which can make the program
inefficient
15 What do you mean by sorti9ng What are the different types ?
Sorting means arranging the array elements in a specified order i.e. either ascending or descending order. Different type
of sorting techniques are selection sort, bubble sort, heap sort and quick sort
16 What is selection sort?
The sorting technique in which the computer keeps on finding the next smallest element and bring it to the appropriate
position is known as selection sort process
17How bubble sort technique functions? In bubble sort, two adjacent elements are compared and brought to their
positions. If they are not in proper order
Notes on constructors

Q1.Define constructor?
Ans. A constructor is a special member function of a class that is automatically called for initialization when an object
is created of the class.

Q2. When is constructor called?


Ans. A constructor is called automatically when an object of the class is created.

Q3. State the characteristics of constructor?


Ans. Constructor has the following characteristics.
a. constructor is having the same name of the class name to which it belongs
b A constructor has no return type not even void.
c. constructor is automaticall or implicitly called.
d. constructor is having only one job to initialize the object
e. constructor should be declared as public

Q4. How many types of constructor are there?


Ans there are 2 types of constructor
1.Parameterized constructor
2 Default or non Parameterized constructor

Q5. Explain default constructor


Ans . A constructor that accepts no parameter is called as non-parameterized or default constructor. If no constructor
is defined by the programmer java automatically supplies a default constructor. It initializes the data members with
valid default values.
Example:- class Abc {
int a,b;
Abc() // default constructor
{ a=0; b=0;}

Q6. What is parameterized constructor


Ans.A constructor with one or more argument is said to be parameterized constructor .it initializes the data members
with parameter passed at the time of object creation.
Example:- class Abc {
int a,b;
Abc(int a1,int b1) // is parameterized constructor
{ a=a1; b=b1;}

Q7 What is constructor overloading?


Ans When there are more than one constructor in a class with different parameterlist is called as constructor
overloading ?
Example:- class Abc {
int a,b;
Abc() // default constructor
{ a=0; b=0;}
Abc(int a1,int b1) // is parameterized constructor
{ a=a1; b=b1;}
Q8 Write a statement to create the object of a class ?
Ans. public static void main(String args[])
{ Abc obj1 = new Abc(); // uses default constructor
{ Abc obj1 = new Abc(12,24); // uses parameterised constructor

Q9. what is new operator?


Ans new operator is used to create the object of a class.

Q10. what do you mean by instantiation?


Ans Instantiation means allocating space for a new object.
String notes
1.State two methods by which we can concatenate two strings ?
by using concat() method and + operator
2.Name four methods which are used to compare strings in Java? equals(),
equalsIgnoreCase(), compareTo(),compareToIgnoreCase()
3.What is the difference between length() and capacity() functions? Length() returns the number of
characters in the string while
capacity() returns the maximum number of characters that can be stored in a string object
4.What is the output of the following statement? String
x=”Hello” ;
System.out.println(“Length of string is “+x.length();
System.out.println(“Capacity of string is “+x.capacity());
Ans. Length of string is 5 Capacity of string is 21 (Since x is initialized with “Hello” when it is created
its length is 5. Its capacity is 21 because room for 16 characters is automatically added
.
5.What is the difference between String and StringBuffer objects?
Ans . The String objects are immutable i.e. once created, they cannot be changed. If any change occurs in a
string object, then original string remains unchanged and a new string is created with the changed string.
StringBuffer objects are mutable. These objects can be manipulated and modified as desired.
6.What is a wrapper Class? Give an example
Ans. Java’s primitive data types are data values and not class objects. Wrapper class convert primitive data
types as objects. These are part of Java’s standard library java.lang We can create an object of Byte type
from its wrapper class as follows. Byte b= new Byte(5). // a byte object created having value 5.
7.What is the difference between read() and readLine() method?
Ans Read() method reads one character at a time where as readLine() method reads collection of characters
at one time
8.Name the wrapper class of char, byte, long, boolean, int, short, float and double?
Ans Character, Byte, Long, Boolean, Int, Short, Float, Double
9.Name the API package that contain wrapper classes?
Ans . Java.lang
10. Write the two ways in which you can assign a text string”TOGETHER” to a string variable?
Ans a. String a = “TOGETHER”;
b. char b[]= {‘’T’,’O’,’G’ …}; String x= new String(b);

functions of string class


method of string class are accessor methods
1 charAt(int index) this function will extract a single character from the given index . the return type of this
function is char.

Eg: String str=”Computer”; char ch=str.charAt(3); will extract “p” .

2.substring(int start index ,int end index) this function will extract the new string form this string .it will
extract the characters starting from starting index uptill ending index .it will not include the ending index in the
new string. The return type is String.
Eg: String str=”computer”; System.out.println(str.substring(3,6)); =”put”

Substring(int index) if only one index is given then it will extract the string from that index uptill end of the
string.

Eg System.out.println(str.substring(3)); =”puter”

3.int length() this function will print the length of a string

Eg System.out.println(str.length());=8

4. int indexOf(char ch): this method will print the index no of the first occurrence of the character in the
string. The return type of the index of function is int . if the character is not found in the string it will return -1.
Eg System.out.println(str.indexOf(‘m’)=2

5 int lastIndexOf(char ch) this method will print the index no of the last occurrence of the character in the
string. The return type of the index Of function is int . if the character is not found in the string it will return -
1. Eg System.out.println(str.lastIndexOf(‘r’)=7

6.String concat(String s1) this function will add or concat the given string at the end of the current String:
return type is string

Eg String str1=”good”; str2=”luck”; System.out.print(str1.concat(str2));=”good luck”

7 +(concatenation operator) it is also usedto add two or more String ,character,numbers with a string: return
type is string

Eg String str1=”good”; str2=”luck”; System.out.print(str1.+str2);=”good luck”

8.boolean endsWith(String s) checks whether the current string ends with the specified string or not the
return type is boolean

Eg String str1=”hard work never fails”;str.endsWith(“fails”);=true

9.boolean startsWith(String s) checks whether the current string starts with the specified string or not the
return type is boolean

Eg String str1=”hard work never fails”;str.startsWith(“fails”);=false

10 int compareTo(String s1) this function compare two string lexicographally in the order in which they
appear in dictionary. Return type is integer and it produces three output 1 positive no 2. Negative no 3. Zero. If
first string is greate r than the second it will give positive value . if first is smaller than it will give negative . for
equal string it will give zero. Eg int x= “Raman”.compareTo(“Arora”)=17

int x=”Arora”.compareTo(“Raman”)= -17

11.boolean equals (String str) will compare two string for equality the return type is boolean .eq
“one”.equals(“ONE”)= false

12 boolean equalsIgnoreCase(String str) will compare two string for equality ignoring the cases (capital and
small) the return type is boolean .eq “one”.equals(“ONE”)= true
13. replace (): This function will a character from the string with another string

Eg: str.replace(‘a’,’e’) will replace all ‘a’ from the string with ‘e’

14. trim() : this function will truncate all the leading and the trailing spaces

15 capacity(): it will return the maximum no of characters that can be entered into the string return
type is int

16. toString() returns the string itself return type is string

17 valueOf() will return string representation of the passed arguments return type is string

Character class

1.what is character class?

Ans: Character class is a class of java.lang package whose instance or object can hold single character data.

2.What is the difference between String and String Buffer class

Ans: String class String Buffer class

1. The object of String class are 1. The object of Stringbuffer class immutable (not change able) are
mutable(changeable) they once initialized its content can be changed and modified . cannot be
modified.

2. The object of string class can 2. The object of stringBuffer class may or maynot use new op- must
use new operator to create erator to create the object the object

3.What is capacity() function.


Ans : The length of the string buffer class is reffered to as the capacity of the string buffer object. It returns the
maximum no of characters that can be entered in the current object.
int n=15;
StringBuffer str=new StringBuffer(n);
Str=”Jhansi”;
int len=str.length();==6
int c=str.capacity();==15
4.append(x): this function will add x character to the end of str ing buffer object. Str.append(3);
5.insert(pos,x)= this will add x characters at the specified position pos
6.delete(beg,end)= this will delete characters at index from beg toend
7.reverse()=reverse the content of string Buffer.
8.Write the statement of the Character class for the following:
a. Check the character(c) is an upper case or not.
boolean ans=Character.isUpperCase( c);

b. Check the character(c) is an lower case or not.


boolean ans=Character.is LowerCase( c);
c. Check the character(c) is an alphabetor Digit or not.
boolean ans=Character.isLetterOrDigit( c);

d. Check the character(c) is an alphabet or not.


boolean ans=Character.isLetter( c);

e. Check the character(c) is a Digit or not.


boolean ans=Character.isDigit( c);

f. Check the character(c) is a blank space or not.


boolean ans=Character.isWhiteSpace( c);

g.convert a capital letter to lowercase or vice versa.


Char ch=Character.toLowerCase(c );
char ch=Character.toUpperCase(c );

10.Write a Statements to perform the following Task:


1. to read a string from the keyboard:- String str=br.readLine();
2. to convert a numeric string to an integer type =Integer.parseInt(n);
3.To read a character from the key board= char ch =(char)br.read();
4.to convert a number to string= String str=Integer.toString(24);=”24”
String str=Double.toString(1.4)=”1.4”
5. Convert a numeric string to double: double y= Double.valueOf(num);
6. Convert a numeric string to long: long x=Long.valueOf(num);
Notes on loops

1. What are loops? How many types of loops are there in Java? The iteration statements are also
called loops or looping statements. There are three kinds of loops in Java. The are for loop, while
loop and do while loop
a. Loops are of two types what are they? Exit control Loop and Entry Control Loop
2. What is an entry control loop? The looping statements in which the test expression is evaluated
before entering into the body of the loop is known as entry control loop. Eg. While loop and for loop
3. What is an exit control loop? The looping expression in which the test expression is evaluated after
the body of the loop is executed is known as exit controlled loop egg. Do while loop
4. When we will use for loop? For loop is used for a fixed number of iterations. Here the programmer
knows beforehand how many times the loop will be executed.
5. What are multiple initializations and multiple update expression? If in a for loop. More than one
variable are initialized and more than one variable are updated then it is known as multiple
initialization. Eg for(i=1,sum=0;i<=ni;sum+=I,++i)
6. What is an infinite loop and how is it created? The loop which goes on executing without any
stoppage is known as infinite loop. An infinite loop can be created by skipping the condition. Eg
a. int I; for (i=1; ;i++) b. for( ; ; )//all three skipped
7. What do you mean by delay loop? A loop can be used to create a delay loop. This can be done to
pause they control as needed by the user during programming. The body of the loop does not
contain meaningful operation to perform egg. Int i=1; while (i<=10) { i++; }
8. What do you mean by an empty loop? An empty loop is a loop without any statement in its loop
body. The effect of an empty loop is that the control variable gets updated and loop terminates as

For Loop While Loop Do while loop


For loop is used when While loop is used when Do while is used when
number of iterations to number of iterations to number of iterations to
be performed are be performed are not be performed are not
known known known
9. It is an entry 10. It is an entry 11. It is an exit controlled
controlled loop controlled loop loop
Do while will be
May not get executed if May not get executed if
executed at least once
the condition is false in the conditions are false
even if the condition is
the beginning in the beginning
false in the beginning
soon as the condition evaluates to be false. For (i=1;i<=100;i++);
12. Difference between while and do while Difference between while and do while loop

While Loop Do while loop


The while loop does not execute at The do while loop will be executed at
all if the condition is false in the least once even if the condition is
beginning false
While loop is an entry control loop Do while loop is an exit control loop

13. What is a break statement? A break statement enables a program to skip over part of the code. It is
used in while, do-while, for loops. It skips the rest of the loop and jumps over to the statement
following the loop. Break statement used in switch case terminates a code sequence associated with
case. Break used in a nested loop will only break the loop in which it is contained.
14. How can we use the break statement in Java? In Java, the break statement can be used in three
ways 1. To terminate a statement sequence in a switch statement. 2. To exit a loop 3. As a form of
goto
15. What is continue statement? Continue is one type of jump statement. It skips the rest of the loop
statements and causes the next iteration of the loop.
16. Strike out the difference between Break and Continue statements? A break statement inside a
loop will abort the loop and transfer control to the statement following the loop whereas continue
statement will just abandon the current iteration and let the loop start the next iteration.
17. Which elements are needed to control a loop? The elements that control a loop are 1. The
initialization expression 2. The test expression 3. The update expression. 4. The loop body
18. Write the Syntax of for loop, while loop, do while loop
For loop:
For (initialization; test condition; update expert)
{// body of loop
}
Initialization eg int i=1;
while( test condition ) while( i<=10)
{ update expression ; { i++;}
}

dowhile : initialization
do
{
// body of loop
update expression ;

} while( test condition ) ;

You might also like