1.
Characteristics of Java :
a. Purely Object Oriented,
b. Write Once Run Anywhere (WORA):
c. Java programs are portable, ie. can be carried to different
machines in the form of bytecode.
d. Platform independent, Java programs are both compiled and
interpreted on different JVMs.
e. It is an open product,(free download).
f. Java is a strongly typed language : every variable and expression
has a type and all values assigned are checked for compatibility
by the compiler.
g. It is case sensitive: capital and small are considered to be
different.
h. supports multimedia, has built in graphics.
i. It can be used to build distributed application where data or
resources can be accessed from any networked computer easily.
j. Robust :The programs can handle unexpected errors.
k. Secure: while the programs are transferred on the net, any
changes occurring in the program are trapped as errors .
l. Multithreading :It allows to perform several tasks simultaneously.
2. Types of java programs: i) Internet applets: Small programs that are
embedded in web pages and run within a web browser . They can access
the resources of a remote system . ii) Stand alone applications : program
reads from and writes to the files only on a local computer .They have a
main() function .iii) Servlets. iv)Java Beans .
3. Object : An object is a software bundle of variables and related methods.
It is an identifiable entity with characteristics (variables /state) and
behaviour (methods ). It is an instance of a class
4. Class : A class represents a set (collection) of objects that share common
characteristics and behaviour. It is a blue print to create objects. It is also
called an object factory.
5. Methods (functions): It is a self contained program entity that accepts one
or more inputs, processes them and can return only one value.
6. Relation between object and class : An Object is an instance of a
class .The class is an abstract representation of the object.
7. Class as Object factory : A class contains all the statements required to
create an object ,i.e the attributes to represent the state of the object and
methods that describe the operations the object can perform . By
providing initial values to depict the state of an object , new object can
be created.
8. Abstraction : The act of representing essential features without including
the background details. Eg. We can drive a car without knowing about the
machinery or internal mechanism .
9. Encapsulation :The wrapping up of data and functions (that operate on
that data )into a single unit (class )is known as
encapsulation .Encapsulation is a way to implement data abstraction as
encapsulation hides the details of the implementation of an object .
10. Inheritance : The process by which an object of a class (child class
/derived class /sub class) acquires the properties of another class (parent
class /base class /super class).
11.Polymorphism: The ability to exist in more than one form. Function
overloading and constructor overloading implement Polymorphism .
12. JVM: The java interpreter is known as the Java Virtual Machine. It is an
abstract machine designed to be implemented on the top of existing
processors. It hides underlying operating system from the java application.
It takes byte code as input and gives the output after executing the
bytecode.
13. API (Application Program Interface): These are libraries of compiled code
that can be used in programs.
14.Bytecode: It is an intermediate code obtained when a java program
(source code) is compiled. It is the machine instruction for the JVM. It is
platform independent i.e. runs on any Operating System .
15.Java Character Set: A set of valid characters (letters, digits or sign) that the
language can recognize.
16.Unicode : A two byte character set with characters representing almost all
characters in almost all human alphabets like English, Chinese, Arabic etc.
They are represented by using escape sequence \u followed by a four
digit hexadecimal number. Eg: Unicode for A(ascii value 65) is ‘\u0041’.
17.Tokens: The smallest individual unit in a program. It is a series of
characters that ends with a whitespace . The five java tokens are KILOS i.e.
keywords, identifiers, literals, operators and separators .
18.Keyword: These are reserved words that convey a special meaning to the
language compiler. They cannot be used as identifiers. Eg : void, int, while,
if etc.
19.Punctuators: The separators used in java are called punctuators .{,},(,),”,.,
[,],,,etc.
20.Identifiers: It is a general terminology for names given to
variables ,objects, classes, functions & arrays .
21.Rules to form identifiers: i) Can use only alphabets, digits, underscore and
dollar sign characters. ii)must not begin with digit, iii) should not be a
keyword, a boolean literal or a null.
22.Convention for naming Identifiers: i) names of public methods and
instance variables begin with lower case letters. ii) For names with
multiple words, the first letter of the second and sub sequent word should
be in capital to enhance readability. iii)private and local variables should
use lowercase letters and underscores. iv) class names and interface
names should begin with an upper case letter. v) constants should be
made using all capital letters and underscores (eg Math.PI).
23.Literals: A constant value is called a literal. It gives the exact
representation of the data .Eg ,11, 29.7,’p’, “pincode”. Literals never
change their value during a program run.
24.Types of literals:
a) Integer literal or Integer constant: Positive or negative numbers
and 0 are called integers. These numbers do not have a decimal
(point). Eg. -5,70,0,-13.Three types of integer in java are : decimal
,octal(starts with a 0) and hexadecimal (starts with 0x).
b) Real literal or floating literals. Numbers with a fractional part
having at least digit before the decimal and one digit after the
decimal. Can exist in Fractional form and Exponential form (has
two parts: mantissa and exponent). The mantissa must be either
an integer or a proper real literal .Mantissa is followed by a letter
E or e and the exponent .The exponent must be an
integer .Mantissa is followed by a letter E or e and the exponent .
The exponent must be an integer.
c) Boolean literals: A Boolean value can be either true or false.
d) Character literals or Character Constant: A Character is a
distinctive mark or symbol ,alphabet (small or capital) or digit
enclosing it in single quote .E.g.,’u’,’(’,’*’,’4’ are some character
literals .Escape sequence used to represent non-graphical
characters as ’\n’, ‘\t’, ‘\0’(null character).
e) String Literal: A String is a sequence of characters enclosed in
double quotes. E.g. ”SJIIT”.
25.Data types in java: i) Primitive ii) Reference type
26.Integral -> byte, short, int, long. Fractional -> float, double.
Non-numeric->char, Boolean
a) byte 8 bits (1 byte) -128 to +127 ie.-27 to 27 -1
b) short 16 bits (2 bytes) -32,768 to +32,767 ie. -215 to 215 -1
c) int 32 bits (4 bytes) -2 billion to +2 billion ie .-231 to 231 -1
d) long 64 bits (8 bytes) -10E18 to +10E18 ie. -263 to 263 -1
e) float 32 bits (4 bytes) -3.4E+38 to 3.4E+38.
f) double 64 bits (8 bytes) -1.7E+308 to 1.7E+308
g) char 16 bits (2 bytes) 0 to 65,535 unicode characters,
h) boolean 8 bits(8 bytes) true/false
27.Reference type: Data element whose value is an address. Eg: Arrays,
classes and interfaces. Also called composite data type or user defined
data type or Non Primitive datatype.
28.Variable: A named memory location which can hold data value of a
particular type.
29.Scope of variable: The program region within which a variable is
recognized or accessible. A variable is accessible only within the set of
curly brackets it is declared in.
30.Instance variables: The variables defined within a class, which provide
identity to the objects. Each object has its own copy of these variables.
Also called data members.
31.System class: This predefined class enables java to use the computer
resources like VDU & keyboard.
32.The object out: It is an object of the System class. It refers to the standard
output device ie. VDU
33.println(): method in the out object of System class to print and change
the line. print() Print and wait in the next column of same line.
34.main(): It is the first method that gets executed. There can be only on
main. It calls other methods.
35.Operator and operands: The operations are represented by operators and
the objects of the operation are referred as operands. Eg in the
expression a+b, a and b are operands and +is the operator.
36.Unary operators: Operators that act on one operand. Unary + and unary -.
If a=5 then -a means -5 and +a means 5. Increment and decrement
operators are also unary operators.
37.Increment and decrement (++ and --): They are unary operators. ++adds 1
to its operand and – subtracts one. Prefix operators (++a and --a) follow
change-then-use rule. Postfix operators (a++ and a--)follow use-then-
change rule.
38.Binary operators: Operators that act upon two operands. +,-,*,/ and
%,>,<,==,>=,!=etc..
39.Relational operators: Six relationships that operands have with one
another. >,<,>=,<=,= = and !=.
40.Difference between = and = =. Assignment operator = assigns values
whereas relational operator = = cheeks if 2 values are equal.
41.Logical operators: &&(short circuit and), ||(or), !not. These are used to
construct complex decision making statements. They have lower
precedence than relational operators. a>b || a== ++b
42.Shorthand operators(arithmetic assignment operators): +=,-=, *=,/= and
%=. They combine an arithmetic op and an assignment op and eliminate
the repeated operand to allow a condensed approach.
43.Ternary operator(?:) : It stores a value depending upon a condition. It
requires three operands.
Eg. Char result =mk>=40?’P’:’F’.It has a lower precedence than other
operators . SysOP(mK>40?”Pass”:”Fail”);
Suppose sales =600; comm=500+ sales >1000?200:50 ;will output 200
and not 550 .b’coz + is done first. Eg 2comm=500+ ( sales >1000?200:50)
44.Significance of operator precedence: It determines the Hierarchy ie. Order
in which expressions are evaluated : (i) Parenthesis() (ii) Unary operators
(++,--) (iii) Library function(iv)Multiply(*) and Divide (/,%) (whichever
comes first). Ternary op(?:) has low precedence while = has the lowest.
45.Math class defined in java.lang package has several functions: Math.sin(x),
Math.cos(x), Math.tan (x) for angle in radians, Math.pow(x,y) x raise to y,
Math.exp(x)e raised to x, Math.log (x) natural logarithm, Math.log10(x),
sqrt(x), Math.ceil(x) round-up, Math.floor(x) round-down, Math.rint(x)
rounds off to nearest integer(affinity towards even ans for .5), Math.abs(x)
absolute value (removes negative sign), Math.max(a,b), Math.min(a,b)
works for int, float, long & double. Math.random() returns a random
number between 0 and 1(including 0 but excluding 1). Math.round(x)
always returns an int. All most all other functions return double values.
Math.max(), min(), abs() may return int if all arguments are int.
46.Pure and Mixed expression : an expression where all operands of same
data type(pure), different data types (mixed).
47.Type conversion: Process of converting one predefined data type to
another. 2 types: implicit, explicit .
48. Implicit(type promotion/coercion): In mixed expressions, java
converts all operands upto the largest operand so as not to lose
information. Priority: String, double, float,long then int.
49.Explicit conversion(type casting): User defined cast that forces a
conversion .Eg (float)5/2.
50.Control flow statements. Loops and if. They regulate the order in which
statements get executed.
51.Block /compound statement: A group of zero or more statements within
braces(curly brackets).
52.Syntax for class declaration: <access specifier> / <modifier> class <class
name> {statements;} No memory is allocated when class is declared
because class is only a blueprint. Memory space is allocated only when
objects of the class type are created.
53.Selection/decision making: offer choice of different paths of execution
based on the outcome of an expression. Eg: switch and if-else.
54.Switch: A multiway -branch selection statement where execution depends
on the value of an expression. Can be used for byte, short, int and char
only and NOT for Strings and real numbers. Each case value must be
unique, range not allowed, default is optional,break to terminate the
statement sequence.
55.Iterative statements: while, for and do-while are iterative statements
(loops) that repeatedly executes a set of statements depending on the
truth of a condition.
56.Entry control(for/ while) and Exit control(do while) loops.
57.Jump statements: break – to exit a loop and continue to begin the next
iteration ignore the current iteration. return may also be considered to be
a jump statement as it send the control back to calling fn. System.exit(0)-
to exit the program.
58.Modifiers: keywords that modify the way the class can be accessed. Also
called access specifiers. public (anywhere), protected: (accessed in the
same package as well as in subclasses anywhere), private(only within the
class itself not to subclass also). default (is not a keyword) when access
modifier is not specified. These can be accessed by any class within the
package also called package-access(not a keyword.
59.Methods may be static(modifier) (class methods): object creation not
required, can be accessed directly without obj in the class, from outside
the class using classname. Eg: Math.sqrt().
60.Non static methods require object creation. Eg. Object of String class
required to call function of String class. Eg:s1.toUpperCase() where s1 is an
object of String class.
61.Modifier final: Keyword final makes a variable act as constant whose
value cannot be changed during program execution.
62.null or empty statement: it may have only a ;(semicolon). It is used when
syntax requires a statement but logic does not.
63.Member variables/Data members of a class can be: class variables(static)
only one copy for the whole class and instance variables(a separate copy
for each instance (object)).
64.Errors: They produce incorrect o/p or terminate the execution. 2 types:
Compile time and Run time. Compile time: Syntax errors missing ; or } or
“ .undeclared variables, assigning incompatible types. Run time: division
by zero(NaN), accessing element/indexOutOfBoundsException of
array/string. Converting invalid String to number. Logical errors are
difficult to find as they produce incorrect results but are not flagged by the
system.
65.*Exception: It is a condition caused by a Run-time error. Exception
handling (try-catch) detects an exceptional circumstance and reports it so
that appropriate action can be taken. The keyword try is used to preface a
block that is likely to cause an exception. A catch block catches the
exception thrown by the try block and handles it appropriately. A finally
block can be used to place code that must be executed no matter what
happens.
66.Scanner Class: It is a class from the java.util package, that reads primitive
types and strings without using wrapper classes. It splits input into
substrings(tokens) separated by delimiters(default is space).Scanner
sc=new Scanner(System.in);to accept data using next(), nextInt(),
nextLine() from the keyboard. Eg int no=sc.nextInt(); char
ch=sc.next().charAt(0).
67.Functions may be: Computational (Math.sqrt(), Math.cos()etc.),
Manipulative(equals(), isUpperCase()) function returns true or false,
Procedural functions perform an action and have no explicit return
value(System.out.println()).
68. Why function ?: i)Abstraction: hiding details, ii) reuseability iii) modular
prog: divide prog into smaller tasks.
69. Function prototype :the first line of the function definition that tells the
program about the type of the value returned by the function and the
number and type of arguments. eg: public void add(int a , int b)
70.Function signature: The function name, number and type of arguments.
Eg: add(int a, int b)
71.Use of return statement: i) to exit from a function ii) to return a value to
the calling function.
72.Void datatype: Used as a return type for functions that do not return any
value. It refers to an empty set of values.
73.this keyword: the member function of every object have access to this
keyword, which points to the current object itself. The this keyword
represents an object that invokes a member function as it stores the
address of the object that is calling the member function.
74.Function Overloading: A function name having several definitions in the
same scope but different by the number or type of arguments. Two or
more functions having same name. It implements OOP Principle
Polymorphism.
75.Pure functions(accessor): Functions that do not change their parameters.
It can take both primitive data and objects as parameters. Return value is
primitive or a new object that is created in the function.
76.Impure functions(modifier functions or mutator):They change the state of
their parameters. Here parameters are always Passed by reference(objects
or array).Not all passed by reference are impure.
77.*read(): is used to read a character from BufferedReader(asc code) as in
int. readLine() reads a string terminated by Enter.
78.A Constructor is that unit of a class which is used to initialize the data
members. It has the same name as the class name. It has no return type. A
constructor is called automatically when ever an object of the class is
created. Its never called explicitly.
79.*Importance of constructors: If data members(variables) of a public class
are declared as private, it is not possible to assign values to those variables
from another class. To assign values to such variables public constructors
are needed.
80.Default constructor: If the user does not define any constructor, a default
constructor without any parameters which assigns default values to the
member variables is provided by java.
81.Parameterized Constructor: A constructor that takes arguments is called
Parameterized Constructor. The values passed to these arguments are
passed to the object when it is created.
82.Formal parameters: The arguments in the first line of definition of the
function or constructor as arguments is called formal parameters.
83.Actual parameters: The arguments passed when the function or
constructor is being called. Can be variables or Literals. add(4,5) add(a,b)
84.Constructor Overloading: When two or more constructor are defined in a
class, it is known as constructor overloading. It is a feature of
POLYMORPHISM.
85.Wrapper Classes: These are defined in java.lang package, have a number
of unique tools(methods) for handling primitive data types and objects.
They can convert primitive data types into objects and vice versa. Eg: to
convert number to String object. String str=Integer.toString(123); String
to integer int n=Integer.parseInt(str); double
d=Double.valueOf(“123.45”);
86.Visibility(access) modifiers: These are used to restrict access to certain
variables and methods. Three types are public, protected and private. By
default it is friendly (not a keyword)
87.Public: accessible to the entire class as well as other classes and other
packages.
88.Protected: visible in all classes /subclasses in the same packages and also
subclasses in other packages.
89.Friendly/default (not keyword): It is a limited version of public. It is
accessible only in the same package.
90.Private: highest degree of protection. Accessible only within their own
class. Cannot be inherited.
91.*Finalize() methods are almost the opposite of constructor. It is a way for
an object to clean up after itself. It is similar to destructors in c++. In java
we don’t need to use it at all Finalize();
92.Single Inheritance: Java supports only one parent class. It does not
implement multiple inheritance directly(more than one parent
class).Multiple inheritance is implemented using a secondary inheritance
path in the form of interfaces.
93.Packages: Grouping of related classes and interfaces. Import statement
enables groups of classes to be available only if they are needed. Eg:
import io.*, awt, util, long packages.
94.Autoboxing: primitive data be converted to object. Eg : Double n=5.7; 5.7
which is a double(primitive) gets converted to its class type Double.
95. Boxing : Converting any primitive datatype to an object(non primitive)
forcefully. Eg: Integer.toString().
96.UnBoxing: Converting an object to a primitive. Eg Integer.parseInt()
97. Strings:Java offers Character class, String class and StringBuffer classes.
ii) Character class : its objects can hold single character. It has methods
like isDigit(ch), isLetter(ch), isLetterOrDigit(ch), isUpperCase(ch),
isTitleCase(ch), which return Boolean value true or false.
toUpperCase(ch), toLowerCase(ch)
iii) String class : its object can hold immutable (unchanging)strings. It has
accessors methods like charAt(), compareTo(), concat(), indexOf(),
length(), replace(), toString, toUpperCase(), toLowerCase(), substring(),
startsWith(), endsWith(),equals(),equalsIgnoreCase(), trim() etc.
98.Array: A finite set of homogeneous data elements stored in contiguous
memory locations under a single variable name.
99.Subscripted/Array variables: A user defined name to identify a set of
adjacent memory locations. Variables that have a subsucript/index.
100. Subscript or index: It is an integer that can identify a specific memory
location. For example: int ar[10],size =10, subscripts of array ar can be
from 0 to 9.
101. General format for declaring a one dimensional array variable:
Datatype array_name[];
102. General format to allocate memory to a one dimensional array:
array_name =new datatype [size];
103. General format to initialise a one dimensional array with given values:
Datatype array_variable[]={value1,value2,value3,…….value n};
int num[]={25,3,12,69};
104. Length: It’s a field used to get the number of elements in a 1-D array:
int x=arrname.length;
105. Double Dimensional array: Array referred by two subscripts, rows and
columns. ar[0][0] is the element in first row, first column.
106. General format to create a 2D -array : Datatype array_name[][]=new
datatype[m][n]; where m is the no. of rows and n is the no. of columns in
the array. The index of every array starts at 0. Example of an integer array
of 3 rows and 5 columns. int arr[][]=new int[3][5];
107. Array are passed by reference: Since java implement as array as an
object, it is passed by reference. So any change taking place in the array in
the method is reflected in the original array.
108. General format to pass an array while calling a method:
methodName(array_name); example search(ar)
109. Linear searching: This takes in an unarranged array of values. The value
is looked for in a sequence beginning from the first array element until it is
searched or till end of array if it is not found.
110. Binary Searching :This take place in an array arranged in ascending (or
descending) order. The middle index of the array is calculated. The value
to be searched is compared with the middle positioned array element. If
value is less than the array element, the upper bound changes to get the
middle index ,so that the search now takes place only in the first half of
the array ,the above process is repeated till the value is located at the
middle position.
111. Bubble Sorting: The adjacent element of the array are compared. When
the array needs to be arranged in ascending order, if the left element is
greater than the next element , they have to be interchanged/swapped .
112. Selection Sort: To arrange in ascending order, the smallest element
needs to be selected and exchanged with the first position element in the
array . Again, the smallest element from the remaining elements is
selected and exchanged with second array element. The process continues
till all elements are arranged. If array needs to be arranged in descending
order, select the largest element.
113. *To make a duplicate of an array :
System.arraycopy(a[],st.index,b[],st.index,no of elements)
114. Extends: Extends clause is a way to declare that one class is a subclass of
another. OOP principle Inheritance.
115. Throws keyword is used to inform that an error has occurred whereas
throw forces an exception .
116. Worked out examples of scanner class:
public static void main (String args[])
{
Scanner sc=new Scanner(“Neil Jacob Jose ”);
while(sc.hasNext())
{
System.out.print(word+””);
} //while }//main
public void main()
{
Scanner sc=new Scanner(“1,2,3,4,5,6,7,8,9,10”).use Delimiter(“,”);
while(sc.hasNextInt())
{
int num=sc.nextInt();
if(num%2==0)
{System.out.print(num+””);}
}//while}//main
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print(“Enter your name and marks”);
String name=sc.next();sc.nextLine();
int marks= sc.nextInt();
System.out.print(name+””+marks);}//main
117. next(): reads the next word(token)from the keyboard or scanner class
object and shifts pointer. While reading from keyboard next() should be
followed by a nextLine() to take care of enter key pressed.
118. nextDouble(): reads a double value from the keyboard or an existing
scanner class object. Pointer shifts.
119. nextLine():reads an entire string till enter is pressed or string ends.
120. hasNext():checks availability of tokens in a scanner class object. Returns
True/false.
121. hasNextInt(): returns true if int values exist in the sc object and return
false in any other case.
122. public static void main()
{ Scanner sc=new Scanner(System.in);
try
{ System.out.print(“Enter an integer”);
Int n=sc.nextInt();
System.out.print(“You entered “+ n);
}//try ends
catch (InputMismatchException e)
{ System.out.print(“mismatch in input” +e);
}//catch ends}//main
123. *Recursive function : A function that calls itself.
Worked our example: to find value of mn.
long power(long m,long n)
{if (n==1) return m;
else return (m*power(m,(n-1)));
}
124. *Interface: An interface(like a class) is a collection of methods that
indicate a class has some behaviour in addition to what it inherits.
Interfaces can be instantiated.(new can not be used).
Interface item //example
{ static final int code= 1001;//constants
Static final String name=”fan”;
Void display(); }// interface ends