0% found this document useful (0 votes)
9 views26 pages

JAVA Notes

Uploaded by

ghoshsoumya183
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views26 pages

JAVA Notes

Uploaded by

ghoshsoumya183
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

JAVA EVOLUTION :-

Java is a general purpose Object oriented programming language Developed by the sun
Microsystem of USA in 1991. Originaly called Oak by James Gosling, one of the
inventors of this language.
FEATURES OF JAVA:-
1. COMPILED AND INTERPRETED:- Usually a computer language is either compiled
or interpreted. JAVA combine both these approaches thus making a JAVA into
two stage System. First JAVA compiler translate source code Which is knows as a
bytecode. Bytecode are not machine instruction. In the second stage the
interpreter takes this bytecode and generate machine code that is executed by
the Machine. We can say that JAVA is both complied and interpreted.
2. PLATFORM INDEPENDENT AND PORTABLE:- The most significant contribution of
JAVA over the other language is its portability. JAVA program can be easily moved
one Computer system to another, anywhere .It can execute any of the operating
system. This ensures that JAVA is a Portable and platform independent language.
3. OBJECT ORIENTED:-JAVA is a true object oriented language. Almost everything in
JAVA is an object. All programs codes and data reside within class and object.
4. ROBUST AND SECURE :- JAVA is a robust a language. It provides many safeguards
to ensure reliable code. It has strict compile time and runtime checking for data
type. It has the concept of exception handling which captures serious error and
eliminates any risk of crashing the system.
Security becomes an important issue for a language that is used for
programming on internet. JAVA provides a big amount of security.
5. DISTRIBUTED:- JAVA is designed as a distributed language for creating
applications on networks. It has the ability to share both data and the programs.
JAVA application can open and access and remote objects on internet as easily as
they can do in a computer system.
6. SIMPLE,SMALL,FAMILIAR:- JAVA is is a very simple languages.
HOW TO JAVA DIFFERS FROM C AND C++ :-
JAVA AND C :-
1. JAVA is a Object Oriented Programming (OOP) languages but C is a Procedural
programming languages.
2. JAVA does not include the C unique statement keywords sizeof, and typedef .
3. JAVA does not contain the data type struct and union.
4. JAVA does not define the types of modifier keywords auto, extern, register,
signed and unsigned.
5. JAVA does not support explicit pointer type.
6. JAVA does not have a preprocessor therefore we cannot use #define, #include,
#ifdef .
7. JAVA adds new operators such as instanceof and >>>
8. JAVA adds labeled break and continue statement.
9. JAVA adds many features required for Object Oriented Programming.
JAVA AND C++ :-
1. JAVA does not support operator overloading.
2. JAVA does not have template classes as in C++.
3. JAVA does not support multiple inheritance of classes.
4. JAVA does not use pointers.
5. There is no header file JAVA.
. JAVA communicates with a webpage through a special tag <APPLET>

SIMPLE JAVA PROGEAM :-


class Sampleone
{
public static void main(String[] args)
{
System.out.println(“JAVA Is better than C++”);
}
}
OUTPUT :- JAVA is better than C++
 EXPLANATION OF THE ABOVE PROGRAM :-
CLASS DECLARATION :-The first line
class Sampleone
declares a class, which is an object oriented construct. As stated earlier , JAVA is a
true object-oriented language and therefore, everything must be placed inside a class.
Class is a keyword and declares that a new class definition follows. Sampleone java
identifier that specifies the name of the class has to be defined.
OPENING BRACES:- Every class definition in JAVA begins with an opening braces “{“ and
ends with a matching closing braces”}”.
THE MAIN LINE:- The third line,
public static void main(String[] args)
defines a method named main(). Every JAVA application must application a main()
method. This is the starting point for the interpreter to begin the execution of the
program. A java application can have many number of classes but only one of them
must include a main method to initiate its execution. (Note that java applets will not
use main method at all).
Public: - The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes. This is similar to the
c++ public modifier.
Static: Next appears the keyword static, which declares that this method as one that
belong to the entire class. The main method must always declares as static since
interpreter uses this method before any objects are created.
Void:- The type modifier void states that the main method does not return any value.
String[] args : - All the parameter methods are declared inside a parentheses. Here
String[] args declares a parameter name args, Which contain an array of object of String
type.
The Output line:- The only executable line in the program is
System.out.println(“Java is better than c++”);
This is similar to printf() in c and cout<< in c++.The println() is a method of out object
,which is a static data member of system class. The method println() always appends a
newline character to the end of the string.
More of java:-
Write a java program to compute the square root of a number.
 Import java.lang.Math;
class Squareroot
{
Public static void main(String[] args)
{
double x=5;
double y;
y=Math.sqrt(x);
System.out.println(“Y: “+y);
}
}
OUTPUT:- Y: 2.23607;
Note that use of + symbol. Here the + acts as the concatenation operator of two
strings. The value y coverted into a string representation before concatenation.
Note that the first statement in the program is
Import java.lang.math;
The purpose of this statements is to instruct the interpreter to load the Math class from
the package lang.
Comments:- JAVA permits both single line command an multi line command. Single
line command denoted by // and multi line command denoted by /* .
AN APPLICATION WITH TWO CLASSES:-
Class Room
{
float length;
float breadth;
void getdata(float a,float b)
{
Length=a;
Breadth=b;
}
}
class RoomArea
{
public static void main(String[] args)
{
float area;
Room room1=new Room();
room1.getdata(14,10);
area=room1.length*room.breadth;
System.out.println(“Area : “+area);
}
}
Program defines two classes Room and RoomArea. The Room class defines two
variables and one methods to assign values to these variables. The RoomArea contains
main method.
The main method declares a local variable area and a Room type object room1 and
then assign values to the data memebers of Room class by using the getdata()
method.Finally area Prints the the results.
Document Section
Package statement
Import statement
Interface statements
Class Definition
Main method

JAVA PROGRAM STRUCTURE:-

 The document section comprises a set of command line.


 Package statement declares a package name.
 Import statement is used to load something.
 Interface statement means declaring a class.
 Class definition means declaring multiple class.
 Main method is used for executing a program.
JAVA TOKENS:-
Smallest individual unit in a program is called Token.
There are five types of token in java
1. Reserved Words
2. Identifiers
3. Literals
4. Operators
5. Separators
KEYWORDS:-
Keyword means reserved word. Java language has 50 keywords. Keyword has a
specific meaning in java .we cannot use them as names of the variables class etc. All
keywords should be written in lowercase letter.
Java keywords :-
abstract assert Boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface

long native new package

private protected public return


short static strictfp super
switch synchronized this throw
throws transient try void
volatile while
IDENTIFIERS:- Identifiers are programmer designed token . They are used for naming
classes,objects,methods,variables,labels,packages and interface in a program.
Java Identifiers has the following rules:-
1. They can be alphabet, digits, underscore and dollar sign characters.
2. They must not begin with a digits.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
5. Identifiers must be meaningful.
JAVA SEPARATORS:- There are many types of java separators
Parenthesis { }
Braces ( )
Brackets [ ]
Semicolon ;
Comma ,
Period .
JAVA STATEMENTS :-
1. Expression statements : Java has seven types of expression statements:-
Assignment,Pre-Increment,Pre-Decrement,Post-Increment,Post-
decrement,Method call and allocation,Expression
2. Labelled statements
3. Control statements
A. Selection statements
i. If
ii. If else
iii. Switch
B. Iteration statements
i. While
ii. Di
iii. For
C. Jump statements
i. Break
ii. Continue
iii. Return
4. Synchronization statements
5. Guarding statements
MODULE 4: Constants , variables and Data Types :-
Constants:- Constants in java refers to the fixed value that do not change during the
execution of a program. JAVA supports several types of constants.
JAVA CONSTANTS:-
1. Numeric constants
i. Integer Constants
ii. Real constants
2. Character Constants
i. Character constants
ii. String constants
INTEGER CONSTANTS:- An integers constants refers to a sequence of digits.There are
the three types of integers namely, Decimal, Octal, Hexadecimal.
REAL CONSTANTS :- Real Constants are those constant Which is used to represent
fractional number(floating point) constants.
Single Character Constants:- A single character constants contains a single character
enclosed within a pair of Single quote marks. Ex:- ‘A’ ‘5’ ‘;’ ‘ ‘
String constants :- A string character contains a sequence of characters enclosed
between double quotes. The characters may be alphabets,digits anything . Ex:- “Hello
Java” “1997” “?.............!” “5+3”
VARIABLES :- A variable is an identifiers that denotes a storage location used to store a
data values . Unlike constants that remains unchanged during the execution of a
program.
A variable name can be chosen by the programmer in a meaningful way.
As mentioned earlier,variables names may consists of
alphabets,digits,underscore(_),and dollar characters.
1. Variables must not start with a digits.
2. UPPERCASE and lowercase letter are distinct
3. It should not be a keyword
4. Whitespace in not allowed
5. Variables can be of any length.

DATA TYPES:- Every variable in java has a data type. Data types specifies the size and
the type of the values that can be stored

DATA TYPES IN JAVA:-


1. Primitive data type
i. Numeric
A. Integer
a. Byte(size : 1 byte)
b. Short(Size : 2 bytes)
c. Int(Size : Four bytes)
d. Long(Size: Eight bytes , ex:-123L)
B. Floating point :- It support a special value NaN (Not a number)
a. Float(4 bytes Ex -1.23f)
b. Double(8 bytes)
ii. Non-neumeric
A. Character
a. Char(size : 2 bytes)
B. Boolean
a. Boolean(true and false)
2. Non primitive data types:-
A. Classes
B. Arrays
C. Interface
DECLARATION OF VARIABLES:-
Syntax:- datatype variable_name;
Ex:- int count;
float x,y;
double pi;
byte b;
char c1,c2,c3;
READING INPUT FROM THE KEYBOARD:-
Using java.util.scanner class and System.in :-
Ex: - write a java program to input your name from the keyboard

Import java.util.*;
class Input
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println(“Ente your name: “);
String s=sc.nextLine();
System.out.println(“My name is: “+s);
}
}

SCOPE OF VARIABLES:-
Java variables are actually classified into three categoris
 Instance variables
 Class variables
 Local varibles
Instance and class variables are declared inside class .Instance variables are created
when the object are instantiated and therefore they are associated with the objects
Variables declared and used inside methods are called local variables.They are called
because they are not available for use outside the class definition. The area of the
program where the variable is accessible is called its scope.
Type Casting:-
We often encounter the situation, where there is a need to store a value of one type
into a variable of another type. In such situation we must cast the value. The syntax is:
Type variable1 = (type)variable2;
The process of converting one data type to another is called casting. Ex:-
Int m=50;
byte n=(byte)m;
long count=(long)n;

AUTOMATIC CONVERSION:-
For some time it is possible to assign a value of one type to a variable of another type
without casting. This is known as the automatic type conversion.
Fo example int is large enough to hold a byte value. Therefore,
Byte b=75;
Int a=b;
Example of a casting program

class Type_casting
{
public static void main(String[] args)
{
char c= ‘x’;
byte b=50;
short s=1996;
int i =123456789;
long l=1234567654321l;
float f1=3.142f;
float f2= 1.2e-5f;
double d=0.000000987;
System.out.println(“C: “+c);
System.out.println(“B: “+b);
System.out.println(“S: “+s);
System.out.println(“I: “+i);
System.out.println(“L: “+l);
System.out.println(“F1: “+f1);
System.out.println(“F2: “+f2);
System.out.println(“D: “+d);
short s1=(short)b;
short s2=(short)i;
float n1=(float)l;
int m1=(int)f1;
System.out.println(“S1: “+s1);
System.out.println(“S2: “+s);
System.out.println(“N1: “+n1);
System.out.println(“M1: “+m1);
}
}

PROGRAM FOR PRINTING A PRIAMID:-


class Priamid
{
public static void main(String[] args)
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" "+i);
}
System.out.println(" ");
}
}
}
OUTPUT :-
1
22
333
4444
55555
666666
7777777
88888888
999999999

MODULE 5:- OPERATORS AND EXPRESSION:-


An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulation.
Java operator can be classified into a number of categories :-
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators( = )
5. Increment or Decrement operartor( ++ , --)
6. Conditional operator(?:)
7. Bitwise operator
8. Special operator(Instanceof operator, Dot operator)

ARITHMETIC OPERATORS ( +, - , *, /, %) :- It is used to construct mathematical


expression
RELATIONAL OPERATOR (<, <=, >, >=, ==, !=) : It gives true or false value.
LOGICAL OPERATORS ( &&, ||, ! )
BITWISE OPERATOR( & , !, ^, ~, <<, >>, >>>) :- It may not be applied float and
double.
Instanceof operator: - The instanceof operator is a 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. This operator allows us to determine whether the object belongs to
a particular class or not.
EX:-
Person instanceof student
Is true of the object person belongs to the Student class, otherwise it gives false.
DOT OPERATOR:
The dot( . ) operator is used to access the instance variables and methods of class
objects.

PROGRAM :-
class Casting
{
public static void main(String[] args)
{
float sum=0.0f;
int i;
for(i=1;i<=10;i++)
{
sum=sum+1/(float)i;
System.out.println("i: "+i);
System.out.println("Sum: "+sum);
}
}
}
OUTPUT:-
i: 1
Sum: 1.0
i: 2
Sum: 1.5
i: 3
Sum: 1.8333334
i: 4
Sum: 2.0833335
i: 5
Sum: 2.2833335
i: 6
Sum: 2.4500003
i: 7
Sum: 2.5928574
i: 8
Sum: 2.7178574
i: 9
Sum: 2.8289685
i: 10
Sum: 2.9289684

MATHEMATICAL FUNCTION:-
Java supports basic math function through Math class defined in the java.lang
package
Sin(x) : -Return the sine value of the angle x in radians
Cos(x):- Return the cosine value of the angle x in radians
Tan(x):- Return the Tangent value of the angle x in radians
asin(y)- Returns the angle whose sine is y.
acos(y):- Returns the angle whose cosine is y.
atan(y):- Returns the angle whose tangent is y.
atan2(x,y) :- Returns the angle whose tangent is x/y.
pow(x,y):-returns x raised to y (xy)
exp(x):- returns e raised to x (ex)
log(x):- Returns the natural logarithm of x;
sqrt(x): Returns the square root of x.
rint(x):- Returns the truncated value of x.
round(x):- Returns the closest to the argument.
abs(a) :- Returns the absolute value of a.
max(a,b):-Returns the maximum of a and b.
min(a,b) : - Returns the minimum value of a and b.

MODULE 6 :- Decision making and Branching


When a program breaks the sequential flow and jumps to another part of the code .It
is called branching.
Java has three decision making statements:-
1. If Statements
2. Switch statement
3. Conditional operator statements

Decision making with if statement:-


The if is a powerful decision making statement and is used to control the flow
of the execution of a statement . It is basically a two way decision making
statements. It takes the following form :
If ( test expression)
It allows the computer to evaluate the expression first, then depending on
whether the value of the expression is true or false

The if statements can be implemented in different forms:-


1. Simple if statements.
2. If…………..else statements.
3. Nested if…….. else statements
4. else if ladder
SIMPLE IF STATEMENTS:-
The general form of if statements is:
If (test expression)
{
Statement- block;
}
Statement x;
The statement block may be a single statement or group of statements. If the test
expression is true the statement block is executed; Otherwise statement block will be
skipped and the executed will be jump to the statement-X.
Example of if statements :-
class Iftest
{
public static void main(String[] args)
{
int i,count,count1,count2;
float[] weight={45.0f,55.0f,47.0f,51.0f,54.0f};
float[] height={176.5f,174.2f,168.0f,170.0f,169.0f};
count=0;
count1=0;
count=0;
for(i=0;i<=4;i++)
{
if(weight[i] < 50.0f && height[i] > 170.0f)
{
count1=count+1;
}
count=count+1;
}
count2=count-count1;
System.out.println("Number of persion with.....................");
System.out.println("Weight < 50 and height > 170 = "+count1);
System.out.println("Others : "+count2);
}
}

OUTPUT:-
Number of person with.....................
Weight < 50 and height > 170 = 1
Others : 4
The if……else statement:-
The general form of if……else statement is:-
If (test expression)
{
True block statements;
}
else
{
False block statements;
}
Statement X;
If test expression in true then True block witll be executed ; Otherwise false block
will be executed.
Program for finding no. of odd no and no. of even number:-
class Evod
{
public static void main(String[] args)
{
int num[]={50,65,56,71,81};
int even=0,odd=0;
for(int i=0;i<=4;i++)
{
if(num[i]%2==0)
{
even=even+1;
}
else
{
odd=odd+1;
}
}
System.out.println("No of even number: "+even);
System.out.println("No of odd number: "+odd);
}
}
OUTPUT:-
No of even number: 2
No of odd number: 3

Nesting of if………….else:-
If (test condition1)
{
If (test condition2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement – x;
--------------------------->
If the condition1 is false the statement-3 is executed; Otherwise it continues to
perform second test. If the condition2 is true, the statement1 will be evaluated;
otherwise statement 2 is evaluated and then the control is transferred to the
statement-X.
Program for understanding Nested if……else statement:-
class K
{
public static void main(String[] args)
{
int a=325,b=712,c=478;
System.out.println("Largest value 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);
}
}
}
}
OUTPUT:-
Largest value is:
712
------------------------------------------------------------------------------------------>
The else if ladder:-
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;
statement-x;

------------------>
The condition are evaluated from top to downwards. As soon as the true condition is
found, the statement associated with it is executed and the control is transferred to the
statement-X. When all the n condition become false, then the final else containing the
default-statement will be executed .
Else if ladder:-
Syntax:-
if (condition1)
Statement – 1;
else if (condition 2)
Statement – 2;
else if (condition 3)
Statement -3;
.
.
.
..
.
else if (condition n)
Statement – n;
else
Default Statement;
Statement –x;

This construct is known as a else if ladder. The condition are evaluated from the top,
As soon the true condition is found, the statement associated with it is executed and
the control transferred to the statement – x. When all the condition is false ,the final
else containing the default-statement will be executed.
Switch statement:-
Syntax:-
Switch(expression)
{
Case value1:
Block1;
Break;
Case value2:
Block2;
Break;
Case value3:
Block3;
Break;
default:
default – block;
break;
}
Statement – x;

When the switch is executed, the value of the expression is successful compared
against value -1, value2……. If a case is found whose value matches the value of the
expression then the block of statement follows the case are executed.
The break statement at the end of the each block signals the end of a particular case
and causes an exit from the switch statement ,transferring control to the statement x.
The default is an optional case. When present it would be executed if the value of the
expression does not match with any of the case value. If not present, no option takes
place. When all the matches fail control go to the statement x.
Program for understanding switch case:-
import java.util.*;
class Day
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the day number: ");
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thrusday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid statement");
break;
}
}
}

Output:- Enter the day number:


5
Thrusday

You might also like