Java Unit 1
Java Unit 1
*Demo: Demo is a java identifier that specifies the name of the class to be
defined.
*public : public is the keyword that can access specifier that declares the main
method as unprotected and therefore making it accessible to all other classes.
*static : static is a access modifier means we can call this method directly
using class name without belong to entire class not the part of class or object.
*void : void is type modifier, void states thet the main method does not return
any value.
* Documentation section :
> the documentation section comprises a set of comment lines giving the name of
the program, the author and other details.
> java also uses a third style comment /*…*/ known as documentation comment.
> Whatever we written in this section compiler ignores the statement.
*Package statement :
> the first statement allowed in a java file is a package statement.
> this statement declares a package name and informs the compiler that the classes
defined here belong to this package.
Ex: package student;
* Import statements :
> the next thing after a package statement but before any class definitions may be a
number of import statements.
Ex: import student.Test;
> this statement instructs the intrepreter to load the Test class contained in the
package student.
* Interface statements :
> an interface is like a class but includes a group of method declarations.
> this is also an optional section and is used only when wish to implement the
multiple inheritance feature in the program.
* class definitions :
> a java program may contain multiple class definitions.
> classes are essential elements of a java program.
JAVA TOKENS :
Smallest individual units in a program are known as tokens.
1. Keywords :
> keywords have specific meaning in java, we cannot use them as names for
variables, classes, methods and so on.
> all keywords are written in lowercase letters.
> java language has reserved 50 words as keywords.
2. Identifiers :
> identifiers are programmer designed tokens.
> They are used for naming classes, methods, variables, objects, labelks, packages
and interfaces in a program.
> java identifiers follow the following rules to create :
i . they can have alphabets, digits, and the underscore and dollar sign
characters.
ii. They must not begin with a digit.
iii. Uppercase and lowercase letters are distinct.
iv. They can be any length .
v. it should not be a keyword.
3. Literals :
Literals in java are a sequence of characters (digits,letters and other
character) that represent constant values to be stored in variables.
> java language specifies following types of literals :
● Integer literals.
● Floating point literals
● Character literals
● String literals
● Boolean literals
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
● Null literals
4. Operators :
An operator is a symbol that takes one or more arguments and
operates on them to produce a result.
5. Separators :
Separators are symbols used to indicate where groups of code are
divided and arranged.
> they basically define the shape and function of our code.
Ex: () , {} , [] , ; , etc.
DATA TYPES :
VARIABLES :
A variable is an identifier that denotes a storage location used to store a data
value.
> variable may take different values at different times during the execution of the
program
> as mentioned earlier, variable names may consist of alphabets, digits, the
underscore and dollar character, subjects to the following condition :
i. They must not begin with a digit.
ii. Uppercase and lowercase are distinct
iii. It should not be a keyword
iv. White space is not allowed
v. variable names can be of any length.
* Declaration of variables :
Declaration does three things :
i. It tells the compiler what the variable name is.
ii. It specifies what type of data the variable will hold.
iii. The place of declaration decides the scope of the variable.
A variable must be declared before it is used in the program.
Program:
import java.io.DataInputStream;
class Reading
{
public static void main(String args[])
{
DataInputStream in=new DataInputStream(System.in);
int n=0;
float f=0.0f;
try
{
System.out.println(“Enter an integer: ”);
n=Integer.parseInt(in.readLine());
System.out.println(“Enter a float number: ”);
f=Float.valueOf(in.raedLine().floatValue());
}
catch(Exception e)
{
System.out.println(“Input Error”+e);
}
System.out.println(“int number =”+n);
System.out.println(“float number =”+f);
}
}
> Reading input from keyboard can also done by these other ways. :
OPERATORS:
An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations
> operators are used in programs to manipulate data and variables.
> java supports a rich set of operators. We have already used several of them, such as
=, +, - ,* ,etc,,
1. Arithmetic operators :
Arithmetic operators are used to construct mathematical expressions as in
algebra. Java provides all the basic arithmetic operators.
Operator meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ division
% Modulo (remainder)
> these can operate on any built-in numeric data type of java. We cannot use these
operators on boolean type.
> arithmetic operators are used as shown below :
a+b a-b a*b etc
2. Relational operators :
> we often compare two quantities, and depending on their relation, to take certain
decision.
> java supports six relational operators in all, these operators and their meaning are
shown below :
Operator meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
> when arithmetic expressions are used on either side of a relational operator, the
arithmetic expression will be evaluated first and then the results are compared.
> relational operators are results only in true or false
Ex: 4-2<10; o/p: true
2>=4; o/p:false
> relational expressions are used in decision statements such as, if and while to decide
the action of running program.
3. Logical operators :
> in addition to the relational operators, java has three logical operators, they are:
Operator meaning
&& logical AND
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
|| logical OR
! logical NOT
> the logical operators && and || are used when we want to form compound conditions
by combining two or more relations.
Ex: 2==3&&3==2
> like the simple relational expressions a logical expressions also results a value of true
or false, they results according to the below truth table:
> note: * logical AND results true if both operands are true otherwise it results false.
*logical OR results false if both operands are false otherwise it results true.
> the logical NOT operator is use to reverse the result of any expression or condition.
If the result of condition is true, the result will be reversed to false
4. Assignment operators :
> assignment operators are used to assign the value of an expression to a variable.
We have seen the usual assignment operator ‘=’.
> in addition, java has a set of ‘shorthand’ operators which are: +=, -=, *=, /=, %=.
Ex: x += 2; is equivalent to x = x + 2;
> advantages of shorthand operators are:
1. What appears on the left-hand side need not be repeated and therefore it
becomes easier to write.
2. The statement is more concise and easier to read.
3. Use of shorthand operator results in a more efficient code.
6. Conditional operator :
> the character pair ? : is a ternary operator available in java. This operator is used to
construct conditional expression of the form:
exp1 ? exp2 : exp3 ,where exp is an expression.
Ex: x = (a > b) ? a : b;
Here, a>b is evaluated, if a is bigger (true) then value of a is assigned to x
otherwise (false) value of b is assigned to x.
7. Bitwise operators :
> java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level.
> these operators are used for testing the bits, or shifting them to the right or left.
> bitwise operators may not be applied to float or double.
> list of bitwise operators:
Operator meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill
8. Special operators :
> java supports some special operators of interest such as instanceof operator and
member selection operator (.) .
> the instanceof is an object reference operator and returns true if the object on the
left-hand side is an instance of the class given on the right-hand side.
> the dot operator (.) is used to access the instance variables and methods of class
objects.
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
CONTROL STATEMENTS :
The if statement is a powerful decision making statement and is used to control
the flow of execution of statements. It is basically a two-way decision statement and
is used in conjunction with an expression, it takes following form:
if(test condition);
It allows the compiler to evaluate the expression first and then, depending on
whether the value of the expression is true or false , it transfers the control to a
particular statement.
1. Simple if statement :
Syntax:
if(test_condition)
{
statement_block;
}
> the ‘statement_block’ may be a single statement or a group of statements.
> if the test_condition is true, the statement_block will be executed, otherwise the
statement_block will be skipped and the execution will jump to the next statements in
the program.
Example program:
import java.util.Scanner;
class Sum
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int c=0;
System.out.println(“Enter a:”);
int a=scan.nextInt();
System.out.println(“Enter b:”);
int b=scan.nextInt();
if(a!=0 || b!=0)
c=a+b;
System.out.println(“Sum is:”+c);
}
}
2.if-else statement :
Example program:
import java.util.Scanner;
class Big
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println(“Enter a:”);
int a=scan.nextInt();
System.out.println(“Enter b:”);
Int b=scan.nextInt();
if(a>b)
System.out.println(“a is bigger:”+a);
else
System.out.println(“b is bigger:”+b);
}
}
Example program:
class Bigger
{
public static void main(String args[])
{
int a=15,b=20,c=40;
System.out.println(“Bigger is:”);
if(a>b)
{
if(a>c)
System.out.println(a);
else
System.out.println(c);
}
else
{
if(c>b)
System.out.println(c);
else
System.out.println(b);
}
}
}
4. Else if ladder :
There is another way of putting ifs together when multipath decisions are
involved. A multipath decision is a chain of ifs in which the statement with each else is
an if.
Syntax:
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
if(condition_1)
statement_1;
else if(condition_2)
statement_2;
else if(condition_3)
statement_3;
…………
else if(condition_n)
statement_n;
else
default_statement;
This is the syntax of else if ladder, here the conditions are evaluated from the
top if there any condition results true then statements associated with that condition
are executed, and control is transferred out of the else if ladder. When all conditions
result false then the final else containing default statement will be executed.
Example program:
class Big4
{
public static void main(String args[])
{
int a=35,b=10,c=26,d=20;
System.out.println("Bigger is:");
if(a>b && a>c && a>d)
System.out.println(a);
else if(b>a && b>c && b>d)
System.out.println(b);
else if(c>a && c>b && c>d)
System.out.println(c);
else
System.out.println(d);
}
}
5. Switch statement :
When we have many alternatives to be selected, java has a built-in multiway decision
statement known as switch. The switch statement tests the value of a given variable
against a list of case values and when a match is found, a block of statement
Syntax:
switch(expression)
{
case value_1: statement_block1;
break;
case value_2: statement_block2;
break;
…………
case value_n: statement_blockn;
break;
default: default statement;
break;
}
Example program:
import java.util.Scanner;
class Switch
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter two numbers:");
int a=scan.nextInt();
int b=scan.nextInt();
int c=0;
System.out.println("Choice operation to be perform:");
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
int d=scan.nextInt();
switch(d)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
break;
default : System.out.println("Error in input");
}
System.out.println("Result is "+c);
}
}
> the java language provides for three constructs for performing loop operations. They
are:
1. while construct
2. do while construct
3. for construct
1. while statement :
Syntax:
initialization;
while(test_condition)
{
body of the loop;
incrementing;
}
The while is an entry-controlled loop statement. The test_condition is evaluated
and if the condition is true, then the body of the loop is executed. After execution of
the body, the counter variable is increased and once again test_condition is
evaluated; if it is true, the body of the loop is executed once again. This process of
repeated execution of the body of the loop continues until the test_condition becomes
false and control is transferred out of the loop.
Example program:
class Fact
{
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
public static void main(String args[])
{
int n=1; //initializing counter variable
while(n<=10)//test_condition
{
int fact=1;
int temp=n;
while(temp>0)
{
fact *= temp;
temp–; //decrementing counter variable
}
System.out.println(“Factorial of”+n+” is “+fact);
n++;
}
}
}
2. Do while statement :
Since the do while statement is an exit-controlled loop before evaluating the
test_condition for loop, once the body of the loop is executed. It means if
test_condition fails at first evaluation, the body of the loop is executed once.
Syntax:
initialization;
do
{
body of the loop;
}
while(test_condition);
Here, on reaching the do keyword, the body of the loop is executed once and
after test_condition in while is evaluated if it is true once again the body of the loop is
executed. This process continues as long as the test_condition is true. When the
test_condition becomes false, the loop will be terminated and the control goes out of
the loop.
Example program:
class Do
{
public static void main(String srgs[])
{
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
int x=15;
do
{
System.out.println("value of x:"+x);
x++;
}while(x<20);
}
}
3. For statement :
The for loop is another entry-controlled loop that provides a more concise loop
control structure.
Syntax:
for(initialization;test_condition;increment)
{
body of the loop;
}
JAVA METHODS :
> We must add methods that are necessary for manipulating the data contained in the
class.
> methods are declared inside the body of the class but immediately after the
declaration of instance variables.
> declaration syntax:
datatype methodname(parameter_list)
{
method body;
}
> method declaration have four basic steps:
1. The datatype of the value the method returns (datatype).
2. The name of the method (methodname).
3. A list of parameters (parameter_list).
4. The body of the method.
> the datatype specifies the type of value the method would return. Such as int
datatype or void datatype if the method didn’t return any value.
>the method name should be a valid identifier.
> the parameter list is always enclosed in parentheses. This list contains variable
names and types of all the values we want to input in the method.
>variables in parentheses are separated by comma, in the case where no input data
are required the declaration must retain the empty parentheses.
Example:
class Rectangle
{
int length;
int width;
void getData(int x,int y) // method declaration
{
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
length=x;
width=y;
}
}
METHOD OVERLOADING :
> in java, it is possible to create methods that have the same name, but different
parameter lists and different definitions. This is called method overloading.
> this is used when objects are required to perform similar tasks but using different
input parameters.
> when we call a method in an object, java matches up the method name first and
then the number and type of parameters to decide which one of the definitions to
execute. This process is known as polymorphism.
> to create an overloaded method, all we have to do is to provide several different
method definitions in the class, all with the same name, but with different parameter
lists.
> the difference may either be in the number or type of arguments. That is, each
parameter list should be unique.
> example:
class Room
{
float length;
float breadth;
Room(float x,float y) //constructor1
{
length=x;
breadth=y;
}
Room(float x) //constructor2
{
length=breadth=x;
}
int area()
{
return(length*breadth);
MATH CLASS :
Java supports basic math functions through the Math class defined in the
java.lang package.
List some functions defined in the Math class:
Functions Action
sin(x) returns the sine of the angle x in radians
cos(x) returns the cosine of the angle x in radians
tan(x) returns the tangent of the angle x in radians
asin(x) returns the angle whose sine is y
pow(x,y) returns x to the power y
log(x) returns the logarithm of x
sqrt(x) returns the square root of x
abs(x) returns absolute value of x
max(x,y) returns the maximum of x and y
min(x,y) returns the minimum of x and y
Example program:
class math
{
public static void main(String a[])
{
double x;
x=Math.max(20,10);
System.out.println(“Maximum of 20 and 10:”+x);
ARRAYS IN JAVA :
“Array is a linear collection of homogeneous data elements.”
* creating an array:
> Like variables, arrays must be declared and created in the computer memory before
they are used.
> creation involves three steps:
1. Declaring the array.
2. Creating memory locations(size)
3. Initializing array.
> declaration of array:
Syntax: datatype arrayname[]; or datatype[] arrayname;
Ex: int a[];
float[] b;
Note: we do not enter the size of the array in the declaration.
>creation of array :
After declaring an array, we need to create it in the memory. Java allows us to
create an array using a new operator only.
Syntax: arrayname=new datatype[size];
Ex: a=new int[4];
This line create necessary memory locations for the array a and designate it as
int respectively. Now variable a refers to an array of 4 integers.
It is also possible to combine the two steps declaration and creation into one line
Syntax: datatype arrayname[]=new datatype[size];
Ex: int a[]=new int[4];
Example program:
class Array
{
public static void main(String args[])
{
int[] a = {10, 20, 30, 40, 50};
System.out.println("Array elements:");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}