0% found this document useful (0 votes)
77 views22 pages

Java Notes

Class is a blueprint for creating objects that share common attributes and behaviors. An object is an instance of a class. A class encapsulates data members that represent an object's state and member functions that represent its behaviors. Classes act as factories for creating multiple objects. Java programs use primitive data types like int and double, as well as reference types like classes and arrays. Variables store values of a specific data type. Keywords, tokens, identifiers, literals, comments, expressions and statements are the basic building blocks of a Java program. Selection and iteration statements like if-else and for loops control program flow. User-defined functions make code modular and reusable. Constructors initialize objects. Wrapper classes allow primitive types to be
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
77 views22 pages

Java Notes

Class is a blueprint for creating objects that share common attributes and behaviors. An object is an instance of a class. A class encapsulates data members that represent an object's state and member functions that represent its behaviors. Classes act as factories for creating multiple objects. Java programs use primitive data types like int and double, as well as reference types like classes and arrays. Variables store values of a specific data type. Keywords, tokens, identifiers, literals, comments, expressions and statements are the basic building blocks of a Java program. Selection and iteration statements like if-else and for loops control program flow. User-defined functions make code modular and reusable. Constructors initialize objects. Wrapper classes allow primitive types to be
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

Java Notes

CLASSES & OBJECTS:-


1)What is a class? Give example.
A class is a blueprint or template from which multiple objects can be created. All objects of
a class have common characteristics and behavior.eg: A school or a Bank.
2)What is an object? Give example.
An object is an instance of a class. Every object has its own state and behavior that is
defined by its class. An object implements the class in reality.
eg: bankaccount and student.
3)What does class encapsulate?
A class encapsulates the data members and the member functions. Data members
represent state of an object and member function represents behavior of an object.
4) Why is class called a factory of objects?
Class acts as a template to create multiple objects sharing common attributes and
behavior. So, we say class is an object factory.
FUNDAMENTAL CONCEPTS OF JAVA PROGRAMMING
1)Token :A token is the smallest individual unit of a program. eg: keywords, operators.
2)keywords: Keywords are the reserved words that have specific meaning for the language
compiler.
3)Identifiers: Identifiers are the symbolic names given by the programmer to various
program units of Java. Identifiers are the names of variables, methods, classes and
packages etc.
4)Variable:A variable is a named memory location that holds a data value of a particular
data type.
5)constants or literals: Data items that have a fixed data value of any of the data types.
They can be number, text or other information that represents a value.
Types of literals:-
Integer literals:45,-345,67859 etc.
Floating point literals: 45.45677,21E05,-31.6435 etc.
Character literals: ‘1’,’@’,’A’,’\t’, ‘\n’ etc.
6) Data types: It is defined as the set of possible values that a variable can hold. They are
classified into two types.
a)Primitive data type(Fundamental data type):These are basic data types provided by the
language.
The eight primitive data types are byte, short , int, long, char, float, double and boolean.
b)Reference data types: These are derived data types that are created using the primitive
data types. A reference data type is used to store the memory address of an object.
Eg:- class and array are reference data types.
7)Comments:-
Non executable statements of a java program are called as comments.
Sing line comments:- begins with //.
Multiline comments:-/*----------- */
8)Classification of expressions(based on the datatypes of variables):-
a)pure expression:-If an expression has all variables of same data type, then it is known as
pure expression.
Eg:- int a=2, b=4,c;
c=a*b;//(here a &b are int)
a)impure expression:-If an expression has variables of different data type, then it is
known as impure expression.
Eg:- int a=2;float b=3.4f; double c;
c=a*b;//(here a & b are of different data types)
9)Types of conversion:
a) Implicit conversion/automatic conversion/coercion/widening:
In an impure expression, values of lower data type are promoted to higher datatype
automatically by the compiler.
b) Explicit conversion/type casting/manual conversion: This type of explicit conversion
is done by the user using the () operator from higher data type to lower data type.
Eg: int a=10;double b=15.45;
int c=(int)(a+b);
10)Operator precedence: Hierarchical order in which the operators are evaluated in an
expression is known as operator precedence. When an expression has multiple operators
of the same precedence, the expression is evaluated according to its associativity(right to
left OR left to right).
11)Escape Sequence characters:-Non graphical characters can be represented using
escape sequences in Java. An escape sequence character begins with a backslash(\)
e.g: \t for horizontal tab, \n for new line feed.
12)Compound statement(block):- Statements enclosed within curly brackets is called a
block.
SELECTION STATEMENTS:-
These statements execute the code based on certain condition.
Forms of decision making statements:-
❖ if statement
❖ if- else statement
❖ Nested if statement
❖ if-else-if statement
❖ switch statement
dangling else problem:- The ambiguity that arises in a nested if when the number of if
clause is more than the number of else clause is called dangling else problem. It can be
resolved using {}.
ITERATION STATEMENTS:-
Iteration means executing certain statements of a program repetitively.
Loops constructs in java are:
1)for loop
2)while loop
3)do-while loop (Refer syntax in pg 21-22)
2)Counters : variable used to count the repetitions in a loop.
3)Accumulators: variable that accumulates the sum of the values added in each iteration.
int sum=0;
for(int i=1;i<=10;i++)
sum=sum+i; //sum is an accumulator variable.
4) A loop that doesn’t have any statements to be executed in its loop body is called
null loop or empty loop. It is used to generate time delay in a java program.
e.g:for(a=1;a<=10;a++);// here ; after closing brackets indicates body of the loop is not
available so it is called a null loop.
5) Infinite loop:- Loop that does not terminate is called an infinite loop.
E.g:- for(int i=1; ;i++)//missing condition is an example for infinite loop.
USER DEFINED FUNCTIONS:-
1) Functions(Methods):- A method is a subprogram within a main program that performs
a specific task.
2) Need for functions:-
a) Functions make the program modular. The program is divided into smaller units called
functions that make the program easy to debug and maintain.
b) Once a function is defined in a program, it can be called anywhere and used any number
of times to solve a specific problem. Thus it reduces code redundancy.
c) Use of functions ensure better memory management.
d) A function acts as a black box that hides the implementation details to the user.
Function prototype:-
Function header is also known as function prototype. It consists of return type,function
name and parameter list.
Eg:- void compute(int a, int b)
• A function with void as the return type indicates function does not return any value.
• A function with return type has a return statement in the function body to return
the value to the calling function.
• A function can return only one value.
Function overloading:-
Two or more functions or methods within the class having same name but performing
different tasks differentiated by the no. of parameters , data types of parameters or order
of the parameters is known as function overloading. Function overloading implements
polymorphism.
CONSTRUCTORS:-
A constructor is a specialized method of a class that initializes all the data members of a
class each time an instance of the class is created.
Features of Constructor:-
a) A constructor has the same name as class name.
b) Constructor never returns a value. Even void keyword should not be used.
c) Constructor gets invoked automatically whenever an object is created for the given
class.
d)when there are more than one constructor present in a program then the constructors
are said to be overloaded.
Types of constructor:-
a) Default constructor:- Constructor that does not have any parameters.
b) Parameterized constructor:- Constructor that takes parameters.
WRAPPER CLASSES IN JAVA:-
Wrapper classes are predefined classes in java.lang package that are used to wrap
primitive data types to object of that class. The eight wrapper classes are Integer, Byte,
Short, Long, Double, Float, Character and Boolean. The two primary functions of Wrapper
class are:-
a) To provide a mechanism to wrap the primitive data type values in an object.
b) To provide an assortment of utility functions for primitives like converting
primitive types to and from string objects.
Autoboxing:
• Autoboxing is the automatic conversion done by the java compiler from the
primitive types to its corresponding object of wrapper class.
eg: int k=98;
Integer ob1=k;//autoboxing
here primitive int i.e k value is directly assigned to wrapper class object ob1.

Unboxing:
• Unboxing is the automatic conversion done by the java compiler where the object
of wrapper is converted to its corresponding primitive data type.
eg: int x=125;
Integer ob2=new Integer(x);
int y=ob2;//unboxing here the object ob2 value is directly assigned to
primitive type variable i.e y.

ARRAYS:-
An array is a collection of homogenous elements referred by the same name and is stored
in contiguous memory location. An array is a memory structure created that contains data
with similar data type.
The index number of the array used to access the array elements is said to be subscript
of the array.
Types of arrays:-
a) One Dimensional array:- Array that is indexed by a single subscript.
b) Double Dimensional array:- Array that are indexed by two subscripts-one for the rows
and the other for the columns.
Differentiate between the following:
Primitive data type Composite data type
Data types that are provided by java and Data type created by a programmer which
allows specific type of data to be stored by a makes use of primitive data type to create a
variable. variable as per the user’s requirement.
The size is fixed. The size depends on the number of member
variables and their data types.

Coercion Type casting


In a mixed expression the data type of the In a mixed expression data type gets
operands gets converted automatically into converted to another
its higher(compatible) type without the lower(uncompatible)type with the
intervention of the user intervention of the user.( )Operator is
used for type casting .

switch if-else
This statement is a multiple branching It is bidirectional control flow statement
statement
It performs tests on integer as well as It performs tests on integer, float and
character point values. character values

Entry controlled loop(eg:while loop) Exit controlled loop(eg:do-while loop)


The loop condition is tested before The loop condition is tested after
executing the loop. executing the loop once.
The body of the loop is not executed, if the Loop body is executed at least once though
condition is false the condition is false.

break continue
It terminates the loop bypassing the It forces early iteration of loop where the
remaining code in the body of the loop. control goes back for the next iteration of
the loop, skipping the remaining code of
the body of the loop for that particular
iteration.

Binary search Linear search


Works on sorted arrays only. Works on both sorted and unsorted arrays.
Works by dividing the array into two Compares each element of the array, one
segments out of which the search is by one, until the search item is found or all
confined to either of those two segments. elements have been compared.
It is more efficient in case of larger arrays. Tends to become inefficient as the size of
the array increases
Base class Derived class
It is the super class/parent class from It is the sub class/child class which derives
which the properties and behaviour are the properties and behaviour from the
derived. base class
compareTo( ) equals( )
It compares two strings lexicographically. Compares two strings considering case
Returns int value. sensitivity of the given strings.
Returns boolean value.

Pure function(Accessor Method) Impure function(Mutator methods)


A pure function is one which does not An impure function is one which changes
change the state of an object. the state of an object.
e.g:void display( int n) e.g:void display( int n)
{ {
System.out.println(n);} n=n+10;System.out.println(n);}
class Object
A class is a blue print or template to create An object is an instance of a class. Each
an object. It defines the object has its own characteristics /state
variables(attributes) and defined by the class.
methods(behavior) that will be a part of Memory is allocated for each object based
every object that is instantiated from it. on its attributes.
But a class reserves no memory space for
variables.

Call by value/pass by value Call by reference/pass by reference


It is the method of passing a copy of actualIt is the method of passing
parameters to the formal parameters. Any reference(address) of actual parameters to
change in the formal parameters does not the formal parameters and any change
reflect on the actual parameters. made in the formal parameters will be
reflected on the actual parameters.
Primitive datatypes like int, float etc are Reference datatypes like objects and
passed to a function by using pass by value arrays are passed to a function by using
call by reference.

next( ) nextLine( )
It is used to input a word. It is used to input a sentence.
Delimiter used is whitespace Delimiter used is enter key

Composite/user defined/reference Built in/primitive/fundamental datatypes


datatype
Size of these datatypes is based on the Size of the variables of primitive data type
number of elements in the datatype. are fixed.
Eg:class, array Eg. int, float etc.
length( ) Length
It is the string function used to find no.of It is the attribute of an array used to find
characters in a string the no.of elements in the array.
String s= “hello”; int a[ ]=new int[5];
int l=s.length( ); int l=a.length;

Class variables/static variables Instance variables/object variables


Only one copy of the class variable is used Every object will have its own copy of
by entire class, which is shared by all the instance variables.
objects. Declaration of Instance variable.
Declaration of class variable. class test
class test {
{ int x;//x is Instance variable
static int x=10;//x is class variable void main()
void main() {
{ ……
…… }
} }
}
Static variable is created when the class is Instance variable is created when an
first referred to object of the class is created
Any change made to the value of static Changes made to instance variable does
variable is visible in all the objects of the not affect the same variable belonging
given class. to the different object.
Static variable can be accessed using the Non- static variable can be accessed by
class name in different classes. using the object name in different
classes.

private modifier public modifier


A member variable declared as private can A member variable declared as public can
be accessed only in the class in which it is be accessed everywhere(by all the classes
declared. defined within the same package and
different packages) .

nextInt( ) hasNextInt( )
This method receives next token from This method returns true if the next token
scanner object which can be expressed as can be expressed as integer , otherwise
an integer and can be stored in a variable returns false.
of type int.
Return type is int. Return type is boolean

Token Identifier
It is the smallest individual unit in a Identifier is the name given to different
program. data items of the program like variables,
methods , objects etc
boolean literal character literal
Literals having any one of the values of Single character enclosed in single quotes
true or false
Reserves memory of one byte but uses Reserves 2 bytes of memory.
only 1 bit

Constructor Method
Constructors are used to initialize the state Methods are used to perform some
of an object. specific tasks.
The class name and constructor name The class name and the method name
should be same should be different
Constructor does not have a return type Methods should have a return type

Java Operator Precedence Table


Precedence Operator Type Associativity
() Parentheses
15 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
14 Right to left
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Larger number means higher precedence.

Important points:-
1. Keyword used to allocate memory to any array or composite data type: new
2. Methods of scanner class:
i)to input an integer from the standard input stream:nextInt( )
ii) to input a String data from the standard input stream:next ( ) or nextLine( )
3. A package that is imported by default: java.lang
4. A key word to use the classes defined in a package: import
5. Package that contains the class System: java.lang
6. The package that contains the class Scanner: java.util
7. String function to remove blank spaces provided in the prefix and suffix
of a String: trim()
8. The method that converts a String to a primitive integer type.
parseInt( ) & valueOf( ) (Wrapper class methods)
9. Some library classes: String, Math, System etc
10.Access specifier that provides most accessibility is public and least accessibility is
private.
11.Keyword that indicates that a method has no return type: void
12.Keyword that causes the control to transfer back to the method call: return
13.Keyword that distinguishes between instance variables and class variables.
static
14.The OOP’s principle that implements function overloading: Polymorphism
15. Character set used in java : Unicode(16 bits)
16. Default value of a boolean datatype: false
17. Default value of char : ‘\u0000’
18. Keyword of java to define a variable as constant: final
19. To read a character using scanner class method is
char ch =sc.next().charAt(0);//sc is scanner class object.
20.System.exit(0); is a system call that exits current program by terminating running Java
Virtual Machine .This function takes argument as status code . Argument ‘0’ is the status
code which indicates normal termination of the program.

Input/output in java:
• A stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination.
• A source of input data is called InputStream and output data is called OutputStream
• The two types of stream are byte stream and character stream.
• Three predefined objects present in java.lang are
System.in, System.out, System.err
• System.in refers to an input stream managed by the System class that implements
the Standard InputStream. System.in is an InputStream object and it is connected to
the standard input device( keyboard).
• System.out refers to an output stream managed by the System class that
implements the standard OutputStream. It is the object of the OutputStream class
and connected to standard output device monitor, System.err stream is also
connected to monitor.
Scanner class:
• The Scanner class is latest development in java , which allows user to input the
values of various types. The Scanner class is defined in java.util package.
• Syntax to create a Scanner object is :Scanner sc=new Scanner(System.in);
• The scanner class basically works on the principle of tokens in the set of values input
from console.
• A token is a series of characters that ends with a delimiter. Some delimiters which
can be used as token separators are comma(,), fullstop(.),semicolon(;),whitespace
etc. Scanner class uses whitespace as default token separator. A white space
character can be a blank, a tab character, a carriage return, or end of the file.

Method Description
Scanner sc=new Scanner(System.in); Returns the next token as an int. If the
int n=sc.nextInt(); next token is not an integer,
InputMismatchException is thrown.
Scanner sc=new Scanner(System.in); Returns the next token as a long. If the
long n=sc.nextLong(); next token is not an integer,
InputMismatchException is thrown.
Scanner sc=new Scanner(System.in); Returns the next token as a float. If the
float n=sc.nextFloat(); next token is not a float,
InputMismatchException is thrown.
Scanner sc=new Scanner(System.in); Returns the next token as a double. If the
double n=sc.nextDouble(); next token is not a double,
InputMismatchException is thrown.
Scanner sc=new Scanner(System.in); Finds and returns the next complete
String n=sc.next(); token as a String(a token is usually ended
by a whitespace). If no token exists,
NoSuchElementException is thrown.
Scanner sc=new Scanner(System.in); Returns the rest of the current line.
String str=sc.nextLine();
boolean b=sc.hasNextLine(); Returns true if the scanner has another
line in its input, otherwise returns false.
boolean b=sc.hasNextFloat(); Returns true if the next token can be
interpreted as float value, otherwise
returns false.
boolean b=sc.hasNextInt(); Returns true if the next token can be
interpreted as int value, otherwise
returns false.
boolean b=sc.hasNext(); Returns true if the scanner has another
token in its input, otherwise returns
false.

Description of all the inbuilt methods/functions covered in the syllabus


Sl. Method Name Description Example
No
1 void print (any type of Displays the System.out.print(10);
value) output and the System.out.print(12.3);
cursor remains in System.out.print('a');
the same line. System.out.print("Hello ");
2 void println (any type Displays the System.out.println(10);
of value) output and the System.out.println(12.3);
cursor moves to System.out.println('a');
the next line. System.out.println("Hello ");
3 int/float/double Returns the Math.abs(-5); //5
absolute value of Math.abs(-5.5f);//5.5
abs(int/float/double) the argument. Math.abs(-123.456);//123.456
(negative number
to positive number
and positive
number remains
the same)
4 int/float/double/char Returns the Math.max(1,4);//4
maximum value Math.max(1.2f,8.6f);//8.6
max(arg1, arg2) among the Math.max(45.6, 89.90);//89.90
arguments. Math.max('a','A');//97
5 int/float/double/char Returns the Math.min(1,4);//1
maximum value Math.min(1.2f,8.6f);//1.2
min(arg1, arg2) among the Math.min(45.6, 89.90);//45.6
arguments. Math.min('a','A');//65
6 double Returns the square Math.sqrt(4);//2.0
sqrt(int/float/double) root value of the Math.sqrt(25.0f);//5.0
argument. Math.sqrt(625.0);//25.0
7 double Returns the cube Math.cbrt(8);//2.0
cbrt(int/float/double) root value of the Math.cbrt(125.0f);//5.0
argument. Math.cbrt(343.0);//7.0
8 double pow(arg1, arg2) Returns the value Math.pow(1,2);//1.0
of arg1 raised to Math.pow(1.2f,3.4f);//finds 1.23.4
arg2 Math.pow(2.3,4.5);//finds 2.34.5
Math.pow('a', 2); //finds 972
9 double Returns the value Math.ceil(4); //4.0
ceil(int/float/double) greater than or Math.ceil(4.2f); //5.0
equal to the Math.ceil(5.0); //5.0
argument. Math.ceil(5.3); //6.0
Math.ceil(-1.2); //-1.0
10 double Returns the value Math.floor(4); //4.0
floor(int/float/double) lesser than or Math.floor(4.2f); //4.0
equal to the Math.floor(5.0); //5.0
argument. Math.floor(5.3); //5.0
Math.floor(-1.2); //-2.0
11 double random() Returns a random Math.random(); //0.3
number between (int)Math.random()*10; // returns
0(inclusive) and any number in the range 0 to 9
1(exclusive)
12 int/long Returns the Math.round(5.6f); //6
round(float/double) rounded value of a Math.round(4.5); //5
number from .5
and above.

13 int length() Returns the total String s="Java program";


no. of characters int L=s.length(); //12
present in the
string object
including space.
14 char charAt(int) Returns the String s="Java program";
character at the char c=s.charAt(2); //v
corresponding char c1=s.charAt(s.length());
index position. If //Error
the index position char c2=s.charAt(s.length()-1);
is not found, then // m
it raises a run-
time error
StringIndexOutOf
Bounds
Exception.
15 int Returns the first String s="Java program";
indexOf(char/string) occurrence of the int i1=s.indexOf('a'); //1
character or string int i2=s.indexOf('A');//-1
present in the int i3=s.indexOf("va"); //2
string object. If
the
character/string
is not found then
it displays the
index position as -
1 by default.
16 int Returns the first String s="Java program";
indexOf(char/string, occurrence of the int i1=s.indexOf('a', 3);//3
character or string Searches for 'a' from 3rd index
int) present in the onwards, since it is present at 3rd
string object from index itself, it will return the same
the specified index number.
staring index by
the user.
17 int Returns the last String s="Java program";
lastIndexOf(char/stri occurrence of the int i1=s.lastIndexOf('a'); //10
ng) character or string
present in the
string object.
18 boolean Checks whether String s="Java program";
startsWith(string) the string starts boolean b=s.startsWith("J");
with the specified //true
string argument boolean b1=s.startsWith("Jav");
and returns //true
true/false Boolean b3=s.startsWith("j");
//false
19 boolean Checks whether String s="Java program";
endsWith(string) the string ends boolean b=s.endsWith("m");
with the specified //true
string argument boolean b1=s.startsWith("ram");
and returns //true
true/false boolean b3=s.startsWith("Ram");
//false
20 boolean equals(string) Checks the String s1="Java";
equality between String s2="Java";
calling string and boolean b=s1.equals(s2); //true
argument string Here s1 is calling string, and s2 is
and returns true if argument string.
they are exactly
matching with the
case of characters,
otherwise false.
21 boolean Checks the String s1="Java";
equalsIgnoreCase(stri equality between String s2="JAVA";
ng) calling string and boolean
argument string b=s1.equalsIgnoreCase(s2);
by ignoring the //true
case of characters Here s1 is calling string, and s2 is
and returns true if argument string.
they are having
same characters,
otherwise false.
22 String toUpperCase() Returns the string String s1="convert";
in uppercase by s1=s1.toUpperCase();
converting //CONVERT
lowercase
characters to
uppercase.
23 String toLowerCase() Returns the string String s1="CONVERT";
in Lowercase by s1=s1.toLowerCase();
converting //convert
uppercase
characters to
lowercase.
24 String Returns the string String s1="babbage";
replace(char,char) after replacing all s1=s1.replace('b','*');
String replace(string, the occurrences of // *a**age
string) existing String s2="keyboard";
character/string s2=s2.replace("key","Black");
with new //Blackboard
character/string.
25 String substring(int) Returns the part of String s1="Computer";
String substring(int, the string from the String s2=s1.substring(3);
int) specified index //puter
positions. String s3=s1.substring(3, 7);
//puter
26 String trim() Returns the string String s1=" Go to the class ";
after removing the s1=s1.trim();
space before and //Go to the class
after the end of
the string. It does
not remove space
in between the
string.
27 String concat(string) Concatenates or String s1="St. ";
joins the calling String s2="Johns";
string with the String s3=s1.concat(s2);
string present as //St.Johns
the argument.
28 int compareTo(string) Compares the String s1="Laptop";
calling string and String s2="Desktop";
argument string int c=s1.compareTo(s2);
by taking the // subtracts the ascii value of L
difference in ASCII and D and gives the output as
values. It returns positive value indicating that
+ve/-ve/0. If +ve Laptop is greater than the
then calling string Desktop.
is greater than the
argument string.
If it is –ve, then
calling string is
lesser than the
argument string.
If 0, then it
indicates both the
strings are same.
29 int System.out.println("Apple".compareT
compareToIgnoreCase oIgnoreCase("apple"));//0
(string)
System.out.println("Bangalore".com
pareToIgnoreCase("Bangladesh"));//
-11

System.out.println("Banana".compa
reToIgnoreCase("grapes"));
//-5
30 String Returns a int x=12;
toString(number) numerical string String s1=Integer.toString(x);
by converting float y=12.3f;
numbers to string. String s2=Float.toString(y);
double z=12.3;
String s3=Double.toString(z);
31 String Returns a int x=12;
valueOf(number) numerical string String s1=String.valueOf(x);
by converting float y=1.2f;
numbers to string String s2=String.valueOf(y);
double z=67.7;
String s3=String.valueOf(z);

32 boolean Checks and boolean


isUpperCase(char) returns true if the b=Character.isUpperCase('D'); //
character is upper true
case, otherwise
false.
33 boolean Checks and boolean
isLowerCase(char) returns true if the b=Character.isLowerCase('a'); //
character is lower true
case, otherwise
false.
34 boolean isDigit(char) Checks and boolean b=Character.isDigit('5'); //
returns true if the true
character is digit,
otherwise false.
35 boolean isLetter(char) Checks and boolean b=Character.isLetter('D');
returns true if the // true
character is an
alphabet,
otherwise false.
36 boolean Checks and boolean
isLetterOrDigit(char) returns true if the b=Character.isLetterOrDigit('a');
character is // true
alphabet/digit, b=Character.isLetterOrDigit('3');//
otherwise false. true
37 boolean Checks and boolean
isWhitespace(char) returns true if the b=Character.isUpperCase('D'); //
character is upper true
case, otherwise
false.
38 char Converts the char
toUpperCase(char) character from c1=Character.toUpperCase('a');
lowercase to //A
uppercase. char
c2=Character.toUpperCase('B');
//B
char
c3=Character.toUpperCase('$');
// $
39 char Converts the char
toLowerCase(char) character from c1=Character.toLowerCase('A');
uppercase to //a
lowercase. char
c2=Character.toLowerCase('b');
//b
char
c3=Character.toLowerCase('$');
// $
40 byte Converts the String s1="12";
parseByte(number as numerical string byte b=Byte.parseByte(s1); [or]
string) to byte type. byte b=Byte.valueOf(s1);
41 short Converts the String s1="123";
parseShort(number numerical string short s=Short.parseShort(s1); [or]
as string) to short type. short s=Short.valueOf(s1);
42 int parseInt(number as Converts the String s1="123";
string) numerical string int a=Integer.parseInt(s1);
to int type. [or] int a=Integer.valueOf(s1);
43 long Converts the String s1="123";
parseLong(number as numerical string long a=Long.parseLong(s1);
string) to long type. [or] long a=Long.valueOf(s1);
44 float Converts the String s1="123.4";
parseFloat(number as numerical string float a=Float.parseFloat(s1);
string) to float type. [or]float a=Float.valueOf(s1);
45 double Converts the String s1="123.56";
parseDouble(number numerical string double a=Double.parseDouble(s1);
as string) to double type. [or]
double a=Double.valueOf(s1);

46 boolean Converts the String s1="true";


parseBoolean(boolean numerical string boolean
value as string) as true/false to a=Boolean.parseBoolean(s1);
boolean type. [or]
boolean a=Boolean.valueOf(s1);
47 int nextInt() Reads the token Scanner s=new
from the scanner Scanner(System.in);
object as integer. System.out.println("Enter an
integer value");
int x=s.nextInt();
48 float nextFloat() Reads the token Scanner s=new
from the scanner Scanner(System.in);
object as float. System.out.println("Enter an float
value");
float x=s.nextFloat();
49 double nextDouble() Reads the token Scanner s=new
from the scanner Scanner(System.in);
object as double. System.out.println("Enter an
double value");
double x=s.nextDouble();
50 long nextLong() Reads the token Scanner s=new
from the scanner Scanner(System.in);
object as long System.out.println("Enter an long
integer. value");
long x=s.nextLong();
51 String next() Reads a string Scanner s=new
token from a Scanner(System.in);
scanner object till System.out.println("Enter a
it finds first space string");
character.It String x=s.next();
means it reads
only one word
from the user’s
input.
52 String nextLine() Reads a string Scanner s=new
token from Scanner(System.in);
scanner object till System.out.println("Enter a
the user press string");
enter key. It String x=s.nextLine();
means it reads
more than one
word from the
user’s input.
53 boolean hasNextInt() Checks the Scanner s=new Scanner("3 4");
availability of boolean b=s.hasNextInt(); true
integer token in Likewise there are other methods:
the scanner hasNextFloat(), hasNextDouble(),
object. hasNextLong(), hasNext(),
hasNextLine()

Common Syntax Errors with their description


Sl.No Example Error Name
1 int a=10 Statement missing ;
2 int a=1, a=1; Multiple
declarations for a
3 int x=12.3; Possible loss of
precision.
Required int found
double
4 int x; System.out.println(x); Variable x might
not have been
initialized.
5 if(a>b); else without if
System.out.println(a); because if
else condition is
System.out.println(b); terminated by
semicolon.
6 System.out.println(a); Cannot find symbol
a
7 class sample Class or interface
{ expected because
void display() { int x=10; } } the keyword class
is written as Class
8. system.out.println(10); Package system
does not exist.
9 String s="Hello; Unclosed String
literal.
10 class Sample Expected {
void display(){ } }
11 Display() Invalid method
declaration, return
type required.

Common Runtime error or exceptions


Sl.No Example Error Name
1 int x=10, y=0; ArithmeticException-Divide By
int z=x/y; Zero. A Number cannot be divided
System.out.println(z); by zero.
2 System.out.println("Enter an integer"); During the execution, if the user
int a=Integer.parseInt(br.readLine()); enter any other value other than
integer, then it raises the error as
NumberFormatException
3 String s="Code"; StringIndexOutOfBounds, because
System.out.println(s.charAt(s.length() accessing the character at the
); index position which is beyond
the range.
Example: "Code" there are 4
characters in it. The index ranges
from 0 to 3. But s.length() gives
the value as 4 in which this index
number is not found.
4 int x[]={1,2,3,4}; ArrayIndexOutOfBoundsException
System.out.println(x[4]); because accessing the array
element at 4th index which is not
found.
5 In Scanner Class: During the execution, if the user
System.out.println("Enter an enter any other value other than
integer"); integer, then it raises the error as
int a=sc.nextInt(); InputMismatchException

Syntax of all the concepts covered in the syllabus


Sl.No Concept Syntax [or] General Form
1 Single line comment //……………………………..
2 Multiple line comment /*…………………..
…………………….. */
3 Documentation /**………………………….
comment …………………………………
…………………………*/
4 Class definition Class classname
{
data members;
constructors
member methods
}

5 Method definition Access-specifier modifier returntype


methodname(parameter list)
{
statements;
}
6 Method prototype Access-specifier modifier returntype
methodname(parameter list)

7 Default constructor public classname()


{
statements;
}
8 Parameterized public classname(parameter list)
constructor {
statements;
}
9 Variable declaration Datatype variablename;
10 Multiple variable Datatype variable1, variable2,……………variable
declaration
11 Variable initialization Datatype variable;
variable=value;
[or]
Datatype variable=value;
12 Multiple variable Datatype variable1, variabl2,……………..;
initialization Variable1=value;
Variable2=value;
.
.
.
Variable=value;
13 Prefix or preincrement --var;
and predecrement ++var;
14 Postfix or Var--;
postincrement and Var++;
postdecrement
15 if statement if(condition)
{
statements;
}
16 if else statement if(condition)
{
statements;
}
else
{
Statement;
}

17 Nested if statement if(condition)


{
if(Condition)
statements;
}
18 if…else if statement if(condition)
{
statements;
}
else if(condition)
{
statements;
}
.
.
else
{
statements;
}
19 switch statement switch(expression)
{
case label1:
statements;
break;
.
.
.
case labeln:
statements;
break;
default:
statement;
}
20 Ternary Operator Var=expression1?expression2:expression3;
21 while statement while(expression)
{
statements;
}
22 do while statement do
{
statements;
}while(expression);
23 for statement for(initialization; condition; updation)
{
statements;
}
24 Nested while while(expression)
statement {
while(expression)
{
statements;
}
}
25 Nested do while do
statement {
do
{
statements;
}while(expression);
}while(expression);

26 Nested for statement for(initialization; condition; updation)


{
for(initialization; condition; updation)
{
statements; } }
27 Creating an object classname objectname=new classname();
28 Accessing non-static Objectname.datamember;
datamembers/membe Objectname.methodname();
r function in a static
function within the
same class/outside
the class.
29 Accessing static classname.datamember;
datamembers/membe classname.methodname();
r function in a static
function outside the
class
30 Explicit Type Var=(datatype)(var or expression);
conversion or
Typecasting
31 Calling objectname.functionname(arguments)
method/function
32 Calling constructor classname objectname=new
function classname(arguments);
34 Importing single class import packagename.classname;
from the package
35 Importing single class import packagename.subpackagename.classname;
from the sub-package
36 Importing all classes import packagename.*;
from the package
37 Importing all classes import packagename.subpackagename.classname;
from the sub-package
38 private/public private datatype variable;
declaration of public datatype variable;
datamembers
39 static datamember static datatype variable;
declaration
40 Array declaration datatype arrayname[ ]; or datatype [ ]arrayname;
41 Array initialization datatype arrayname[]={v1,v2,……………vn};
42 Finding length of an Var=Arrayname.length;
array
43 Array creation or datatype arrayname[]=new datatype[size];
memory allocation
44 Accessing array Var=arrayname[index value];
element

You might also like