Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
178 views

Java Programs

The document provides examples of Java programs that demonstrate various Java programming concepts like compiling and running a Java program, using print and println methods, declaring and changing variables, arithmetic operators, if/else conditional statements, relational operators, bitwise operators, and the ternary operator. It includes sample code to display text, calculate sums and areas, swap variables, perform bitwise operations, and use conditional expressions. The document also describes operators like member selection, new, cast, and instanceof and provides their syntax and examples.

Uploaded by

muruganv84
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
178 views

Java Programs

The document provides examples of Java programs that demonstrate various Java programming concepts like compiling and running a Java program, using print and println methods, declaring and changing variables, arithmetic operators, if/else conditional statements, relational operators, bitwise operators, and the ternary operator. It includes sample code to display text, calculate sums and areas, swap variables, perform bitwise operations, and use conditional expressions. The document also describes operators like member selection, new, cast, and instanceof and provides their syntax and examples.

Uploaded by

muruganv84
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

CPDP-JAVA (2016-2017) JAVA Programming

4. SAMPLE JAVA PROGRAM


first.java:
import java.io.*;
class sample
{
public staic void main(String args[])
{
statements;
}
}
TO COMPILE AND RUN A PROGRAM IN NOTEPAD (For Above Program)
Compile a Java Program:
Syntax
d:>javac <filename>

Example
d:> javac first.java

To Run a Java Program:


Syntax
d:>java <classname>

Example
d:>java sample

6. STARTING OF JAVA PROGRAM


6.1 To display a Message

display.java:
import java.io.*;
class display
{
public staic void main(String args[])
{
System.out.println(Welcome to JAVA);
}
}

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Compile and Execute:


D:\CARE JAVA >javac display.java
D:\CARE JAVA >java display
Welcome to JAVA
6.2 Sum of Two Numbers
display.java:
import java.io.*;
class display
{
public staic void main(String args[])
{
System.out.println(Welcome to JAVA);
}
}
Compile and Execute:
D:\CARE JAVA >javac display.java
D:\CARE JAVA >java display
D:\CARE JAVA Welcome to JAVA
6.3 Print() And Println() Methods With Back Slash Codes
6.3.1 To understand the effect of print() and println() methods and the back slash codes

Basic1.java
class foundation
{
public static void main (String args[])
{
System.out.print("JAVA is a ");
System.out.println("Simple");
System.out.println("Program\t\t! ! !");

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


}
}
Compile and Execute:
D:\CARE JAVA >java Basic2
Error: Could not find or load main class Basic2
Because Here Class Name is foundation.
D:\CARE JAVA >java foundation
JAVA is a Simple
Program

!!!

Basic2.java
class Basic2
{
public static void main (String args[])
{
System.out.print("JAVA is a ");
System.out.println("Simple");
System.out.println("Program\t\t! ! !");
}
}
Compile and Execute:
D:\CARE JAVA >javac Basic2.java
D:\CARE JAVA >java Basic2
JAVA is a Simple
Program
!!!
6.4 Variable may be changed during the execution of a program

example.java
class example
{
public static void main (String args[])
{

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


int num = 100;
System.out.println("This is a Number : " + num);
num = num * 2;
System.out.print("The Value of num * 2 is ");
System.out.println(num);
}
}
Compile and Execute:
D:\CARE-GROUP >javac example.java
D:\CARE-GROUP >java example
This is a Number : 100
The Value of num * 2 is 200

7. OPERATORS IN JAVA
Operators
An operator is a symbol that performs an operation.An operator acts on some
variables,called Operands and get the desired result,as shown in figure.
Operator
a

Operand
VARIOUS TYPES OF OPERATORS IN DETAIL:

Arithmetic operators
Unary Operators
Unary Minus operator
Increment / Decrement Operator
Assignment Operator
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Relational Operator
Logical Operator
Boolean Operator
Bitwise Operators
Ternary or Conditional Operators

7.1 Program understand a Arithmetic Operators


Arith.java
class Arith
{
public static void main (String args[])
{
int i,j,k,l,m;
i=5;j=3;
k=i/j;
l=j/k;
m=j/l;
System.out.println("The K Value is :" + k);
System.out.println("The L Value is :" + l);
System.out.println("The M Value is :" + m);
}
}
Compile and Execute:
D:\ CARE-GROUP >javac Arith.java
D:\CARE-GROUP >java Arith
The K Value is :1
The L Value is : 3
The M Value is :1
Area.java
class Area
{

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


public static void main (String args[])
{
float tri,b,h;
b=10;
h=50;
tri=b*h/2;
//tri=1/2*b*h;

//250.0
//0

//These two for double type


//tri=1.0/2.0*b*h; //250.0
//tri=0.5*(b*h);
//250.0
System.out.println("Area of Triangle : " + tri);
}
}
Compile and Execute:
D:\CARE-GROUP>javac Area.java
D:\CARE-GROUP>java Area
Area of Triangle : 250.0
7.2 Program for understand the increment/decrement operator (++/- -)
Increm.java
class Increm
{
public static void main (String args[])
{
int x=2;
//x=x++ + 1;
//3
//x = (x++) + (x) + x + 1;
//9
System.out.println("The Value is : " + x);
}
}
Compile and Run:

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


D:\CARE-GROUP>javac Increm.java
D:\CARE-GROUP>java Increm
The Value is: 3
The Value is: 9
7.3 Program for understand the Assignment (=)
Swap.java
class Swap
{
public static void main (String args[])
{
int a,b,c;
a=5;
b=4;
System.out.println("Before Swapping : ");
System.out.println("The Value Of A = : " +a);
System.out.println("The Value Of B = : " +b);
c=a;
a=b;
b=c;
System.out.println("After Swapping : ");
System.out.println("The Value Of A = : " +a);
System.out.println("The Value Of B = : " +b);
}
}
Compile and Execute:
D:\CARE-GROUP>javac Swap.java
D:\CARE-GROUP>java Swap
Before Swapping:
The Value Of A = : 5
The Value Of B = : 4
After Swapping:
The Value Of A = : 4
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Do Yourself:
Exercise:
Write a same Swap program without using third (temp) variable.
7.4 Program for understand the Relational and logical
The main use of relational operators is the construction of conditions in statements, like
this:
if(condition_is_true) statement_to_be_executed
This statement could be applied in a program as follows:
if(a>b) System.out.println(a);
if(a==100) System.out.println(a value equals to 100);
Relational.java
class Relational
{
public static void main (String args[])
{
int x,y;
x=10;
y=20;
if(x<y)
System.out.println("X is less than Y ");
x=x*2;
if(x==y)
System.out.println("X is now equal to Y ");
x=x*2;
if(x>y)
System.out.println("X is greater than Y ");
if(x==y)

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


System.out.println("You won't See this");
}
}
Compile and Execute:
D:\CARE JAVA >javac Relational.java
D:\CARE JAVA >java Relational
X is less than Y
X is now equal to Y
X is greater than Y
7.5 Program for observe the effects of various bitwise operators
There are 7 Bitwise operators in Java. These Operators acts on individual bits (0 and 1) of
the operands. They act on only integer datatypes ,i.e byte,short,long and int.
BITWISE
OPERATOR

DESCRIPTION

Bitwise Complement operator

&

Bitwise and operator

Bitwise or operator

Bitwise xor operator

<<

Bitwise Left Shift operator

>>

Bitwise Right Shift operator

>>>

Bitwise Zero Fill Right Shift operator

Bitwiseand.java
class Bitwiseand
{
public static void main (String args[])
{

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


int x=10,y=11,z;
z=x&y;
System.out.println("z = x&y " +z);
}

//x= 0000 1010 | y = 0000 1011


//z= 0000 1010
// 10

}
Compile and Execute:
D:\CARE JAVA >javac Bitwise.java
D:\CARE JAVA >java Bitwise
z = x&y 10
Bitwiseor.java
class Bitwiseor
{
public static void main (String args[])
{
int x=9,y=11,z;
z=x|y;
System.out.println("z = x|y " +z);
}

//x= 0000 1001 | y = 0000 1011


//z= 0000 1011
//11

}
Compile and Execute:
D:\CARE JAVA>javac Bitwiseor.java
D:\CARE JAVA>java Bitwiseor
z = x|y 11
Bitwisexor.java
class Bitwisexor
{
public static void main (String args[])
{
int x=11,y=12,z;
z=x^y;
System.out.println("z = x^y" +z);

//11=0000
//11=0000
//7

1011, 12=0000 1100


1011 ^12=00001100

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


}
}
Compile and Execute:
D:\CARE JAVA>javac Bitwisexor.java
D:\CARE JAVA>java Bitwisexor
z = x^y 7
Bitwiseshift.java
class Bitwiseshift
{
public static void main (String args[])
{
byte x=11,y=12,z;

//11=0000

System.out.println("~x : " +(~x));


System.out.println("x<<2: " +(x<<2));
System.out.println("x>>2: " +(x>>2));

//-12
//44
//2

System.out.println("x>>>2: " +(x>>>2));


System.out.println("x>>>3: " +(x>>>3));
System.out.println("y>>>3: " +(y>>>3));

//2
//1
//1

1011, 12=0000 1100

}
}
Compile and Execute:
D:\CARE JAVA>javac Bitwiseshift.java
D:\CARE JAVA>java Bitwiseshift
~x : -12
x<<2 : 44
x>>2 : 2
x>>>2 : 2
x>>>3 : 1
y>>>3 :1

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


7.6 Program for a Ternary Operator or Conditional operator (? :)
This operator is called Ternary because it acts on 3 variables. The other name for this
operator is conditional operator, since it represents a conditional statement. Two symbols are
used for this operator ? and:
Its Syntax is Variable = expression 1 ? expression2 and expression 3;
Syntax:
if(exp1 is true)
variable = expression2;
else
variable = expression3;
Ternary.java
class Ternary
{
public static void main (String args[])
{
int i,j,k,l,m;
i=110;
j=142;
k=125;
l=(i>j)?i:j;
m=(k>l)?k:l;
System.out.println("The Biggest of three Number is :" + m);
}
}

Compile and Execute:


D:\ CARE-GROUP>javac Ternary.java
D:\ CARE-GROUP>java Ternary
The Biggest of three Number is : 142

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


7.7 Special Operators of Java
Some other operators are in Java are :

member operator (.)


new operator
cast operator
instanceof operator

Member Operator:
Member operator is also called dot operator since its symbol is a .(dot or period).This
Operator tells about member of a package or a class.Its used in three ways :
Method-I:
We know a package contains classes. We can use . Operator to refer to the class of a
package.
Syntax

Example

Description

Packagename.classname;

java.io.BufferedReader

BufferedReader is a Class in the


Package

Method-I I:
We know that each class contains variables or methods. To refer to the variables of a
Class, We can use this operator.
Syntax

Example

Description

Classname.variable name;

System.out

Out is a static variable in System Class

Objectname.variablename
;

emp.id

id is a variable in Employee Class.


Emp is Employee Class Object

Method-I I I:
We know that a class also contains methods. Using dot operator, We can refer to the
methods of class.
Syntax

Example

Description

classname.methodname

Math.sqrt()

sqrt() is a method in Math Class

Objectname.methodname

br.read()

read() is a method BufferedReader


Class: br is object of BufferedReader
Class

instanceof Operator:

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


This operator is used to test if an object belongs to a class or not. Note that the word
instance means object. This operator can also be used to check if an object belongs to an
interface or not.
Syntax

Example

boolean <variablename> = <object name> instanceof


boolean x= emp instanceof
<class name>
Employee;
Here,we are tesing if emp is an object of Employee Class or not.If emp is an Object of
Employee class,then true will be returned into x,otherwise x will contain false.
7.8 Priority of Operators
When several operators are used in a statement, it is important to know which operator
will execute first and which will come next. To determine that, certain rules of operators
precedence are followed:
First, the contents inside the braces: () and [] will be executed.
Next, ++ and --.
Next,*,/ and % will execute
+ and will come next
Relational operators are executed next
Boolean and bitwise operators
Logical operators will come afterwards
Then Ternary operator
Assignment operators are executed at the last.
8. CONTROL STATEMENTS IN JAVA
cond1.java
class cond1
{
public static void main (String args[])
{
int x,y;
x=10;
y=20;
if(x<y)
System.out.println("Apple");
System.out.println("Orange");
System.out.println("Grapes");
System.out.println("Mango");

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

System.out.println("\n");
if(x>y)
System.out.println("Maruti");
System.out.println("Hyundai");
System.out.println("Tata");
System.out.println("Toyotta");
System.out.println("\n");
if(x<y)
{
System.out.println("Carrot");
System.out.println("Bitter Gourd");
System.out.println("Bottle Guard");
System.out.println("Ridge Gourd");
}
System.out.println("\n");
if(x>y)
{
System.out.println("Keyboard");
System.out.println("Mouse");
System.out.println("Monitor");
System.out.println("Printer");
}
System.out.println("This is Example of Simple If Condition");
}
}
Compile and Execute:
D:\CARE-GROUP> javac cond1.java
D:\CARE-GROUP> java cond1
Apple
Orange
Grapes
Mango
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Hyundai
Tata
Toyotta
Carrot
Bitter Gourd
Bottle Guard
Ridge Gourd
This is Example of Simple If Condition
8.2 Condition Statements - II
8.2.1 Switch statement
Program to using switch display a color name depending on color value

stswitch1.java
class stswitch1
{
public static void main (String args[])
{
char ch='R';
switch(ch)
{
case 'r' :
case 'R':
System.out.println("Red");
break;
case 'g':
case 'G':
System.out.println("Green");
break;
case 'b':
case 'B':
System.out.println("Blue");
break;

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


case 'y':
case 'Y':
System.out.println("Yellow");
break;
default:
System.out.println("No Color");
}
}
}

Compile and Execute:


D:\CARE-GROUP >javac stswitch1.java
D:\CARE-GROUP >java stswitch1
Red

stswitch2.java (Same Program without using break statement)


class stswitch2
{
public static void main (String args[])
{
char ch='R';
switch(ch)
{
case 'r' :
case 'R':
System.out.println("Red");

case 'g':
case 'G':
System.out.println("Green");
break;
case 'b':
case 'B':
System.out.println("Blue");

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


case 'y':
case 'Y':
System.out.println("Yellow");
default:
System.out.println("No Color");
}
}
}
Compile and Execute:
D:\CARE-GROUP>javac stswitch2.java
D:\CARE-GROUP>java stswitch2
Red
Green
Blue
8.2.2 break statement
Program to use a break statement to go to the end of a

block

stbreak.java
class stbreak
{
public static void main (String args[])
{
boolean x= true;
bl1:{
bl2:{
bl3:{
System.out.println("Block3");
if(x) break bl2;
//goto end of bl2
}
//end of bl3
System.out.println("Block2");
}
//end of bl2
System.out.println("Block1");
}
//end of bl1
System.out.println("Out of all Blocks");
}
}
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Compile and Execute:
D:\CARE JAVA>javac stbreak.java
D:\CARE JAVA>java stbreak
Block3
Block1
Out of all Blocks
8.2.3 continue statement
Program to use a continue statement go back in the loop.
stcontinue.java
class stcontinue
{
public static void main(String args[])
{
int i=10;
for(;i>=1;i--)
{
if(i>5) continue;
System.out.println(i + " ");
}
System.out.println(i + " ");
}
}
Compile and Execute:
D:\CARE-GROUP>javac stcontinue.java
D:\CARE-GROUP>java stconitnue
5
4
3
2
1
0
8.2.4 return statement

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Program to return a value from a method
streturn.java
class streturn
{
public static void main (String args[])
{
//call mymethod() and catch the result into res
//Since mymethod() is Static,we can call it using classnmae.methodname()
int res = streturn.myMethod(10);
//display the result now
System.out.println("Result="+res);
}

//this method calculates square value and returns it to main()


static int myMethod(int num)
{
return num * num;
}
}
Compile and Execute:
D:\CARE JAVA>javac streturn.java
D:\CARE JAVA>java streturn
Result=100
8.3 LOOPING
Types of Loops
while loop
do-while loop
for loop
While Loop:

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


This loop is used when there is a need to repeatedly execute a group of statement as long
as a condition is true. If the condition is false, the repetition will be stopped and the flow of
execution comes out of while loop.
class Loop1
{
public static void main(String args[])
{
int i;
for(i=1;i<10;i++);
{
System.out.println(i );
}
}
}
Do Yourself:
8.3.1 Sum of digits using a While Loop
whilesumof.java
//To write a sum of Digits
import java.io.*;
class whilesumof
{
public static void main (String args[])throws IOException
{
int num,t,s;
num=47;
s=0;
System.out.println("The Given Digit is : " + num);
while(num!=0)
{

//Processing
//Cycle-I num=47

Cycle-II num=4

t=num%10;
//t=7,num=47
t=4,num=7
s=s+t;
//s=0+7=7
s=7+4=11
num=num/10;
//num=4
num=0
}
System.out.println("Sum of Digits is : " + s);
//s=11
}
}

CARE GROUP OF INSTITUTIONS

Cycle-III num=0

CPDP-JAVA (2016-2017) JAVA Programming

Compile and Execute:


D:\CARE JAVA>javac whilesumof.java
D:\CARE JAVA>java whilesumof
The Given Digit is : 47
Sum of Digits is : 11
8.3.2 Do-While Loop:
The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use while loop.
It is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
} while (condition);
8.3.2.1 To print the first 10 even numbers.
dowhile1.java:
public class dowhile1
{
public static void main(String[] args)
{
int i=2;
do{
System.out.println(i);
i+2;
}while(i<=10);
}
}
Compile and Execute:
D:\CARE JAVA>javac dowhile1.java
D:\CARE JAVA>java dowhile1
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

2
4
6
8
10
8.3.2.2 (a) Reverse a digits Using Do-While Looping Programs
Doreverse.java:
//Reverse a Digits in do_while loop
class Doreverse
{
public static void main(String args[])
{
int i,a,num,rev=0;
num=234;
do
{
a=num%10;
rev=rev*10+a;
num=num/10;
}while(num>0);
System.out.println("The Reverse of Given Number is : + rev);
}
}
Compile and Execute:
D:\CARE JAVA>javac Doreverse.java
D:\CARE JAVA>java Doreverse
The Reverse of Given Number is: 432
ARMSTRONG NUMBERS:
Armstrong Number in Java: Armstrong number is a number that is equal to the sum of
cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Let's try to understand why 153 is an Armstrong number.
153 = (1*1*1) + (5*5*5) + (3*3*3)
Where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153
Similarly: 153,370, 371,407 are all Armstrong number.
8.3.2.2 (b) To find a Given Number is Armstrong or Not:
Armstrongdo.java:
class Armstrongdo
{
public static void main(String[] args)
{
int c=0,a,temp;
int n=153;
//It is the number to check armstrong
temp=n;
do
{
a=n%10;
n=n/10;
c=c+(a*a*a);
} while(n>0);
if(temp==c)
System.out.println("The Give Number : " + temp + " is a Armstrong number");
else
System.out.println("The Give Number : " + temp + " is Not a Armstrong number");
}
}
Compile and Execute:

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


D:\CARE JAVA>javac Armstrongdo.java
D:\CARE JAVA>java Armstrongdo
The Give Number: 153 is a Armstrong number
8.3.2.3 Java Infinitive do-while Loop:
If you pass true in the do-while loop, it will be infinitive do-while loop.
dowhile2.java:
public class dowhile2
{
public static void main(String[] args)
{
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
Compile and Execute:
D:\CARE JAVA>javac dowhile2.java
D:\CARE JAVA>java dowhile2
infinitive do while loop
infinitive do while loop
infinitive do while loop
This loop is used when there is a need to repeatedly execute a group of statements as long
as a condition is true. If the condition is false, the repetition will be stopped and the flow of
execution comes out of dowhile loop.
Do Yourself:
Write a program to find a given number is Palindrome or not.
Example:
111,121, 131,141, , , , are all Palindrome. If we reverse we can get same number.
8.3.3 for Loop:
The for loop is also same as dowhile loop, but it is more compact syntactically.
The for loop executes a group of statements as long as a condition is true.
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Syntax:
for(expression1;expression2;expression3)
{
statements;
}
To understand the preceding syntax, let us take an example:
for (int x=1;x<=10;x++)
{
System.out.println(x);
}
Example for Loop Program:
import java.io.*;
class forloop
{
public static void main (String args[])throws IOException
{
int x,y;
y=20;
System.out.println("Enter the Table Number");
for(x=0;x<10;x++)
{
System.out.println("This is X : "+x);
System.out.println("This is Y : "+y);
y=y-2;
}
}
}

Compile and Execute:


D:\CARE JAVA>javac forloop.java
D:\CARE JAVA>java forloop
Enter the Table Number

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


This is X : 0
This is Y : 20
This is X : 1
This is Y : 18
This is X : 2
This is Y : 16
This is X : 3
This is Y : 14
This is X : 4
This is Y : 12
This is X : 5
This is Y : 10
This is X : 6
This is Y : 8
This is X : 7
This is Y : 6
This is X : 8
8.3.3.1 Program to calculate a Multiplication Number:
formulti.java
//To Print Multiplication Number (Compile Time Value)
import java.io.*;
class formulti
{
public static void main (String args[])throws IOException
{
System.out.println("Multiplication Table");
int num=16;
System.out.println("Multiplication of Number :" + num);
for(int i=1;i<=10;i++)
{
System.out.println( num + " * " + i + " = " + (i*num));
}
}
}
Compile and Execute:
D:\CARE JAVA>javac formulti.java

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


D:\CARE JAVA>java formulti
Multiplication Table
Multiplication of Number: 16
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
16 * 8 = 128
16 * 9 = 144
16 * 10 = 160
formulti.java
Multiplication table using for Loop: (Run Time Value)
//To Print Multiplication Number
import java.io.*;
class formulti
{
public static void main (String args[])throws IOException
{
System.out.println("Enter the Table Number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine());
System.out.println("Multiplicaation of Number :" + num);
for(int i=1;i<=10;i++)
{
System.out.println( num + " * " + i + " = " + (i*num));
}
}
}
Compile and Execute:

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


D:\CARE JAVA>javac formulti.java
D:\CARE JAVA>java formulti
Enter the Table Number
12
Multiplication of Number: 12
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120
8.3.3.2 Program to find Fibonacci Series without using recursion:
Fibonnacci.java
//Fibonacci Series in Java without using recursion
class Fibonacci
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.println("First 10 Numbers of Fibonacci Series :");
System.out.print(n1+" "+n2);
//printing 0 and 1
for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

//loop starts from 2 because 0 and 1 are already printed

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Compile and Execute:
D:\CARE JAVA>javac Fibonacci.java
D:\CARE JAVA>java Fibonacci
0 1 1 2 3 5 8 13 21 34
8.3.3.3 Program to print Floyds triangle:
This program will prompt user for number of rows and based on the input, it would print
the Floyds triangle having the same number of rows.
FloydTri.java
import java.util.Scanner;
class FloydTri
{
public static void main(String args[])
{
int rows, number = 1, counter, j;
//To get the user's input
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of rows for floyd's triangle:");
//Copying user input into an integer variable named rows
rows = input.nextInt();
System.out.println("Floyd's triangle");
System.out.println("****************");
for ( counter = 1 ; counter <= rows ; counter++ )
{
for ( j = 1 ; j <= counter ; j++ )
{
//Incrementing the number value number++;
System.out.print(number+" ");
}
//For new line
System.out.println();
}
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


}
}
Compile and Execute:
D:\CARE JAVA> javac FloydTri,java
D:\CARE JAVA>java FloydTri
Enter the number of rows for floyd's triangle:
5
Floyd's triangle
****************
1
23
456
7 8 9 10
11 12 13 14 15
D:\CARE JAVA>java FloydTri
Enter the number of rows for floyd's triangle:
10
Floyd's triangle
****************
1
23
456
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
8.3.4 Nested for Loops
We can write a for loop within another for loop. Such loops are called nested loops.
Syntax:
for(expression1;expression2;expression3)
{
statements;
}

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Example:
for(int i=1;i<=3;i++)
{
statements 1;
//these are executed 3 times
for(j=1;j<=4;j++)
{
statements 2; //these are executed 12 times.
}
}
8.3.4 .1Star1.java
class Star1
{
public static void main(String args[])
{
int i,st,r=5;
for(i=1;i<=r;i++)
{
for(st=1;st<=i;st++)
{
System.out.print("*");
}
System.out.println("\t");
}
}
}
Compile and Execute:
D:\CARE JAVA>javac Star1,java
D:\CARE JAVA>java Star1
*
**
***
****
*****
8.3.4 .2Triang1.java
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

class Triang1
{
public static void main(String args[])
{
int i,n,t,st;
n=5;
for(i=1;i<=4;i++)
{
for(t=1;t<=n;t++)
{
System.out.printf("\t");
}
for(st=1;st<=i;st++)
{
System.out.printf("\t\t" + st);
}
System.out.println();
n--;
}
}
}
Compile and Execute:
D:\CARE JAVA>javac Triang1.java
D:\CARE JAVA>java Triang
1
1 2
1 2 3
1 2 3 4
9. INPUT AND OUTPUT
Input represents data given to a program and output represents data displayed as a result
of a program.We are already familiar with the following two statements to display the output:
System.out.print();
System.out.println();
Accepting a Input from the Keyboard
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


A stream is required Keyboard. A stream represents flow of data from one place to
another place.
A stream can carry data from keyboard to memory of from memory to printer or
memory to a file. A stream is always required if we want to move data from one place to another.
9.1 Need of using a Buffered Reader and Stream Reader
Basically, there are two types of streams: input streams and output streams.

Input streams are those streams which receive or read data coming from some other
place.
Output Streams are those streams which send or write data to some other place.
Connect the keyboard to an input to an input stream object. Here, we can use
InputStreamReader that can read data from the keyboard.
InputStreamReader obj = new InputStreamReader(System.in);

In this Statement, we are creating InputStreamReader object and connecting the keyboard
(System.in) to it.
Connect InputStreamReader to BufferedReader,which is another input type of stream. We
are using BufferedReader as it has got methods to read data properly,coming from the
stream.
BufferedReader br = new BufferedReader(obj);
Here, we are creating BufferedReader object(br) and connecting the InputStreamReader
object(obj) to it.
In the above two steps,We got BufferedReader object(br).The two steps can be combined
and rewritten in a single statement as :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Now, We can read the data coming coming from the keyboard using read() and
readLine() methods available in BufferedReader class;
Data
BufferedReader

InputStreamReader

CARE GROUP OF INSTITUTIONS


System.in

Keyboard

CPDP-JAVA (2016-2017) JAVA Programming

Reading data from Keyboard


9.1.1 Accepting a single character from keyboard
Now follow these steps i order to accept in order to accept a single character from the keyboard.
Create a BufferedReader class object(br).
Then,read a single character from the keyboard using read() method as :
char ch = br.read();
Here, the read() methods reads a single character from the keyboard but it returns its ASCII
number,which is an integer . Since, this integer number cant be stored into character type
variable ch, We should convert into char type by writing(char) before the method as:
char ch=(char)br.read();
When read() method is giving IOException,as a programmer,its our duty to do
something in case of the exception.This is called exception handling. Since, at this moment we
dont know how to handle exceptions,let us throw this exception without handling it by writing:
throws IOException at the side of the method() where read() is used.
These concepts are used in the following program while receiving a single character from
the keyboard.

9.1.1(a) To Accept and display a character from the Keyboard


Acceptch.java
//Accept and Display a Single Character from the Keyboard
import java.io.*;
import java.lang.*;
class Acceptch
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


{
public static void main (String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a Character : ");
char ch = (char)br.read();
System.out.println("You Entered : " + ch);
}
}
Compile and Execute:
D:\CARE JAVA >javac Acceptch.java
D:\CARE JAVA >java Acceptch
Enter a Character :
V
You Entered : V
9.1.1(b) Accepting a string from keyboard
AcceptStr.java
import java.io.*;
import java.lang.*;
class AcceptStr
{
public static void main (String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Accepting a String from the Keyboard
System.out.println("Enter a Name : " );
String name = br.readLine();
System.out.println("Entered Name is : " + name);
}
}

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Compile and Execute:


D:\CARE JAVA>javac AcceptStr.java
D:\CARE JAVA>java AcceptStr
Enter a Name:
Vijey
Entered Name is: Vijey
9.1.1(c) Accepting an Integer, Short, Float and Double Value from keyboard
Let us follow these steps to accept an integer from the keyboard.

First, we should accept the integer number from the keyboard as a String.Using
readLine() as :
String str = br.readLine();

Now,the number is in str,i.e. in form of a String.This should be converted into an int by


using parseInt() method of Integer Class as :
int n = Integer.parseInt(str);
For Shorting the Codings,the above two statements can be combined and written as :
int n= Integer.parseInt(br.readLine());

Here, parseInt() is a static method in Integer class,So it can be called using class name as
Integer.parseInt()
Similiarly , For Short,Float and Double :
short s = Short.parseShort(br.readLine());
float f= Float.parseFloat(br.readLine());
double d = Double.parseDouble(br.readLine());
Acceptall.java
//Accepting a Integer,Short,Long and Double.
import java.io.*;
import java.lang.*;
class Acceptall

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


{
public static void main (String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Integer Data Types
System.out.print("Enter a Integer Value : ");
int i = Integer.parseInt(br.readLine());
//Short Data Types
System.out.print("Enter a Short Value : ");
short s = Short.parseShort(br.readLine());

//Float Data Types


System.out.print("Enter a Float Value : ");
float f= Float.parseFloat(br.readLine());
//Double Data Types
System.out.print("Enter a Double Value : ");
double d = Double.parseDouble(br.readLine());
System.out.println("Your Integer Value : " + i);
System.out.println("Your Short Value : " + s);
System.out.println("Your Float Value : " + f);
System.out.println("Your Double Value : " + d);
}
}

Compile and Execute:


D:\CARE JAVA>javac Acceptall.java
D:\CARE JAVA>java Acceptall
Enter a Integer Value : 12
Enter a Short Value : 4
Enter a Float Value : 4.1
Enter a Double Value : 4.5390
Your Integer Value : 12
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Your Short Value : 4
Your Float Value : 4.1
Your Double Value : 4. 5390
//Note:
//This is for Integer.
//This is for Short.
//This is for Float.
//This is for Double.
9.1.1(d) Accepting

It's Range is : -2147483648 to 21474836487(4 Bytes).


It's Range is : -32768 to 32767(2 Bytes).
It accept 7 Digits after decimal point.(4 Bytes).
It accept 18 Digits after decimal point.(8 Bytes).

Other types of Value

Similarly, We can write different statements to accept many other data types from keyboard as
follows :

To Accept a byte Value:

byte b = Byte.parseByte(br.readLine());

To Accept a Boolean Value:

boolean x = Boolean.parseBoolean(br.readLine());
In the above example, we used the classes, such as Byte, Short,Integer,Long,
Float,Double and Boolean,wich belong to java. lang Package. These classes are also called
wrapper classes.
Do Yourself:

To Accepting and display employee details.


Program to get a number limit find Fibonacci Series.
9.2.1 Reading input with java.util.Scanner Class:
We can Scanner class of java.util package to read input from the keyboard or a text file.
When the Scanner class receives input, it breaks the input into several pieces,called tokens.These
tokens can be retrieved from the Scanner object using the following methods :

next() - to read a String


nextByte() to read byte value
nextInt() - to read an Integer value
nextFloat() to read float value
nextLong() to read long value

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

nextDouble() to read double value

To read input from keyboard, we can use Scanner class as:


Scanner sc = new Scanner (System.in);
Now, if the user has given an integer value from the keyboard, it is stored into the Scanner
object(sc) as a token. To retrieve that token, we can use the method:
sc.nextInt().
The following program will make this concept clear.
Acceptscan.java:
// Scanner Sample Program
import java.util.Scanner;
class Acceptscan
{
public static void main (String args[])
{
//To Read a Student id, Student Name and Total
System.out.print("Enter a Student id, Student Name , Total :");
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
String name =sc.next();
float marks =sc.nextFloat();
System.out.println("Student Id :"+id);
System.out.println("Student Name:"+name);
System.out.println("Student Marks:"+marks);
}
}
Compile and Execute:
D:\CARE JAVA\Class-1\06.Input Output>javac Acceptscan.java
D:\CARE JAVA\Class-1\06.Input Output>java Acceptscan

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Enter a Student id, Student Name, Total:
12
Akash
478
Student Id :12
Student Name:Akash
Student Marks:478.0
Do Yourself :

To Read the (Lower Case String) and Convert into a Upper String.
9.2.2 Displaying Output with System.out.printf ()
The following and display the output, printf() method is available in PrintStream class.
This method works similar to printf() function in C.We know that System.out returns
PrintStream class object,so to call the printf() method we can use:
System.out.printf();
The following format character can be used in printf();
%s - String
%c - char
%d - decimal integer
%f float number
%o octal number
%b,%B Boolean Value
%x,%x hexadecimal number
%e,%E number in Scientific notation
%n new line character
An example for using printf() is given below :
System.out.printf(Salary=%f,sal);
Accept9.java
//Reading Input with java.util.Scanner Class
import java.util.Scanner;
class Accept9
{
public static void main (String args[])
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


{
String s1="Hello";
int n=65;
float f=15.1234f;
System.out.printf("String = %s%n num = %d%n Hexa Decimal = %x%n
Float = %f ",s1,n,n,f);
}
}
Compile and Execute:
D:\CARE JAVA>javac Accept9.java
D:\CARE JAVA>java Accept9
String =Hello
num=65
Hexa Decimal=41
Float=15.123400
10. ARRAYS
An array represents a group of elements of same data type. It can store a group of
elements. So, we can store a group of int values or a group of float values or a group of strings in
the array. But we cant store some int values and some float values in the array.

10.1 TYPES of Array:


Arrays are generally categorized into two parts as described here :

Single dimensional arrays (or 1D arrays)


Multi-dimensional arrays (or 2D,3D,.arrays)

10.1.1 Program for Creating a 1D Array


Arrays.java
/An array of the number of days in each month
import java.io.*;
class Arrays
{
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


public static void main (String args[])throws IOException
{
int month_days[] = new int[12];
month_days[0]=31;
month_days[1]=28;
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
month_days[5]=30;
month_days[6]=31;
month_days[7]=31;
month_days[8]=30;
month_days[9]=31;
month_days[10]=30;
month_days[11]=31;
System.out.println("April has " + month_days[3] + " days ");
}
}
Compile and Execute:
D:\CARE JAVA >javac Array2.java
D:\CARE JAVA >java Array2
April has 30 days
10.1.2 Marks of a Student into a 1D Array from the Keyboard and find total marks and
percentage
marks.java
import java.io.*;
class marks
{
public static void main (String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the No. Of Subjects :");
int n = Integer.parseInt(br.readLine());

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


int[] marks= new int[n];
int i;
i=0;
while(i<n)
{
System.out.println("Enter Mark : "+ (i+1) + " ");
marks[i] = Integer.parseInt(br.readLine());
i++;
}
int tot=0;
for(i=0;i<n;i++)
{
tot += marks[i];
}
System.out.println("Total Marks: "+tot);
float per = (float)tot/n;
System.out.println("Percentage is : "+per);
}
}

Compile and Execute:


D:\CARE JAVA>javac marks.java
D:\CARE JAVA>java marks
Enter the No. Of Subjects :
3
Enter Mark: 1
78
Enter Mark: 2
89
Enter Mark: 3
56
Total Marks: 223
Percentage is: 74.333336
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

10.1.3 Program which performs Enhanced Marks Adding (+5) Marks in Each Subject (s)
plusfive.java
import java.io.*;
class plusfive
{
public static void main (String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("<<<Enhanced Marks Adding (+5) Marks in each Subjects>>>");
System.out.println("Enter the No. Of Subjects :");
int n = Integer.parseInt(br.readLine());
int[] marks= new int[n];
int i;
i=0;
while(i<n)
{
System.out.println("Enter Mark : "+ (i+1) + " ");
marks[i] = Integer.parseInt(br.readLine());
i++;
}
for(i=0;i<n;i++)
{
marks[i] = marks[i] + 5;
if(marks[i]>100)
marks[i]=100;
}
System.out.println("Enhanced "+ n +" Subject Marks are Printed Below");
for(i=0;i<n;i++)
System.out.println(marks[i]);
}
}
Compile and Execute:

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

D:\Arrow-Java>javac plusfive .java


D:\Arrow-Java >java plusfive
<<<Enhanced Marks Adding (+5) Marks in each Subjects>>>
Enter the No. Of Subjects:
5
Enter Mark: 1
89
Enter Mark: 2
90
Enter Mark: 3
97
Enter Mark: 4
56
Enter Mark: 5
79
Enhanced 5 Subject Marks are Printed Below
94
95
100
61
84
10.1.4 Program which performs a sorting of group of integer values using bubble sort
technique

sorting.java

Compile and Execute:


D:\Arrow-Java>javac sorting.java
D:\Arrow-Java >java sorting
10.1.5 Creating a (2D) Two Dimensional Array
twoddim.java
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Compile and Execute:


D:\Arrow-Java>javac twoddim.java
D:\Arrow-Java >java twodim
10.1.6 Program which accepts elements of a Matrix and displaying its transpose
matrix.java
Compile and Execute:

11. STRINGS
Most of the data that transmits on Internet will be in the form of groups of characters
such groups of characters are called Strings. For Eg, in a business order form, a person enters
details like his name, credit card number; address, etc., which are all nothing but Strings only.So
a string represents a group of characters.
String s = Java;
Here, s is a variable of the data type String.
Note:
Is String a class or Data type?
String is a class in Java.lang package.But in Java,all classes are also considered as
datatype.So we can take Stirng as a datatype also.
Can we call a class as a data type ?
Yes,a class is also called User-defined datatype.This is because a user can create a
class.
Creating a Strings
There are three ways to create strings in Java:
Way-1

We can create a string just by assigning a group of characters to a string type variable:
String s;
s = Hello;
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Preceding two statements can be combined and Written as :
String s = Hello;
Way-2:

We can create an object to String class by allocating memory using new operator.
This is just like creating an object to any class, like given here:
String s= new Sting(Hello);
Here, We are doing two things.First,we are creating object using new operator.Then,We
are storing the string : Hello into the object.

Way-3:

The third way of creating the strings is by converting the character array into strings.
Let us take a character type array: arrr[] with some characters, as :
char arr[]={c,h,a,i,r,s};

To Understand String Concepts:


stringeg1.java
class stringeg1
{
public static void main(String args[])
{
char arr[]={'G','o','o','d',' ','D','a','y'};
String s = new String("Hello");
//Use String Constructors
String s1 = new String();
String s2 = new String(s);
String s3 = "Hello World";
String s4 = new String(arr);
String s5 = new String(arr,3,3);
System.out.printf(" S1=%s\n S2=%s\n S3=%s\n S4=%s\n S5=%s\n
S=%s\n",s1,s2,s3,s4,s5,s);
}
}
Compile and Execute:
D:\CARE JAVA> javac stringexg.java
D:\CARE JAVA>java stringexg

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


S1=
S2=Hello
S3=Hello World
S4=Good Day
S5= Da
S=Hello
stringeg2.java
class stringeg2
{
public static void main(String args[])
{
char chars1[]={'a','e','i','o','u'};
String s = "Java";
String s1 = new String(chars1);
String s2 = new String(s1);
System.out.println(" String S1 = "+s1);
System.out.println(" String S2 = "+s2);
System.out.println(" String Length S1 = "+ s1.length());
System.out.println(" String Length of S = "+ s.length());
}
}
Compile and Execute:
D:\CARE JAVA> javac stringeg2.java
D:\CARE JAVA> java stringeg2
String S1 = aeiou
String S2 = aeiou
String Length of S1 = 5
String Length of S = 4

stringeg3.java
class stringeg3
{
public static void main(String args[])
{
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


String str1 = " Java";
String str2 = " Program IT ";
int str3 =2301;
String con1 = str1 + str2 + str3;
String con2 = " Core" + str1 + "Book";
String con3 = " Core " + 2 + 3;
String con4 = " Core " + (2+3);

//String Concatenation

System.out.println(con1);
System.out.println(con2);
System.out.println(con3);
System.out.println(con4);
}
}
Compile and Execute:
D:\ CARE JAVA >javac stringeg3.java
D:\ CARE JAVA >java stringeg3
Java Program IT 2301
Core JavaBook
Core 23
Core 5
11.1 String Class Methods
Let us have a look at which methods are available in String class and how they can be
used String concat(String s)
Here,concat is the method name. Since this method belongs to String Class, it can be
called using a String class object as s1.concat ().Here S1 is a sting class object. Please observe
the String s in the parenthesis after the method name. Something like this s1.concat (s2).
String s3 = s1.concat (s2);
11.2 Program to create a Strings and how to use some important methods of string class
stringclassmeth.java
//String Class Methods
class stringclassmeth
{
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


public static void main(String args[])
{
String s1="A book on Java";
String s2 = new String("I Like it");
char arr[]={'D','r','e','a','m','t','e','c','h'};
String s3= new String(arr);
//Display all three Strings
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
//The Length of First String
System.out.println("The Length of s1 = : "+s1.length());

//Concatenate two Strings


System.out.println(" s1 and s2 are joined = : "+s1.concat(s2));
//Concatenate three Strings with +
System.out.println( s1+" from "+s3);
//Test if string s1 starts with A
boolean x = s1.startsWith("A");
if(x) System.out.println(" S1 starts with \'A \'");
else System.out.println(" S1 doesn't starts with \'A\'");
//extract Substring from s2 ,Starting from 0th Char to 6th Char
String p = s2.substring(0,7);
//extract Substring from s3 ,Starting from 0th Char to 8th Char
String q = s3.substring(0,9);
//Concatenate two Strings p and q
System.out.println(p+q);
//Convert s1 into Uppercase to Lowercase
System.out.println("Upper S1= "+s1.toUpperCase());
System.out.println("Lower s1="+s1.toLowerCase());
}
}
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Compile and Execute:


D:\CARE JAVA>javac stringclassmeth.java
D:\CARE JAVA>java stringclassmeth
A book on Java
I Like it
Dreamtech
The Length of s1 = : 14
s1 and s2 are joined = : A book on JavaI Like it
A book on Java from Dreamtech
S1 starts with 'A '
I Like Dreamtech
Upper S1= A BOOK ON JAVA
Lower s1=a book on java

11.3 String and Copy some of the characters of the string into a character array arr using
getchars() Method
strgetchar.java
class strgetchar
{
public static void main(String args[])
{
String str="Hello, this is a book of java ";
char arr[]= new char[20];
//Copying from str into arr starting from 7th Character to 20th Character
str.getChars(7,21,arr,0);
System.out.println(arr);
}
}
Compile and Execute
D:\CARE JAVA>javac strgetchar.java
D:\CARE JAVA>java strgetchar
this is a book
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

11.4 Splitting a String into pieces where ever a space is found


strsplit.java
//Splitting a String
class strsplit
{
public static void main(String args[])
{
//Take a String str which is to be broken
String str="Hello, this is a book of java ";

//Declare a String type array s to store pieces


String s[];
//Split the String where a space is found in str
s=str.split(" ");
//diaplay the pieces from s
for(int i=0;i<s.length;i++)
System.out.println(s[i]);
}
}
Compile and Execute
D:\CARE JAVA >javac strsplit.java
D:\CARE JAVA >java strsplit
Hello,
this
is
a
book
of
java
11.5 String Comparison

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


The relational operators like >,>=,<,<= , = = and != cant be used to compare the strings.
On the other hand, methods like ; compareTo() and equlas() should be used in String
comparison.
Example: 1
Program to Compare two Strings using = = Operator :
strcomp1.java
// String Comparison - I
//[= =]
class strcomp1
{
public static void main(String args[])
{
String s1="Hello";
String s2= new String("Hello");

if(s1==s2)
System.out.println("Both are Same");
else
System.out.println("Not Same");
}
}
Compile and Execute
D:\CARE JAVA>javac strcomp1.java
D:\CARE JAVA>java strcomp1
Not Same
Example: 2
strcomp2.java
// String Comparison - I I
//[ = = ]
class stringeg5_1
{

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


public static void main(String args[])
{
String s1="Hello";
String s2="Hello";
if(s1==s2)
System.out.println("Both are Same");
else
System.out.println("Not Same");
}
}
Compile and Execute:
D:\CARE JAVA>javac strcomp2.java
D:\CARE JAVA>java strcomp2
Both are Same
Difference between = = and equals () while comparing Strings?
= = Operator compares the references of the String objects. It doesnt compare the contents
of the objects.
equals () method compares the contents. While comparing the Strings, equals () method
should be used as it yields the correct result.
strcomp3.java
// String Comparison - III
//[== and Equals,equalIgnoranceCase]
class strcomp3
{
public static void main(String args[])
{
String s1="Hello";
String s2="Hello";
String s3="hello";
if(s2==s3)
System.out.println("Both are Same");
else
System.out.println("Not Same");
System.out.println("\n Check by using S1==S2 Symbol : " + (s1 == s2));
System.out.println("\n Check by using S2==S3 Symbol : " + (s2 == s3));
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


System.out.println("\n Check With S1.equals(S2) Method : " + s1.equals(s2));
System.out.println("\n Check With S2.equals(S3) Method : " + s2.equals(s3));
System.out.println("\n Check with S2.equalIgnoranceCase(S3) : " + s2.equalsIgnoreCase(s3));
}
}
Compile and Execute:
D:\CARE JAVA>javac strcomp3.java
D:\CARE JAVA>java strcomp3
Not Same
Check by using S1==S2 Symbol : true
Check by using S2==S3 Symbol : false
Check With S1.equals(S2) Method : true
Check With S2.equals(S3) Method : false
Check with S2.equalIgnoranceCase(S3) : true
11.6 Converting a Case and String:
casing.java
Compile and Execute

11.7 Searching for a String in Linear Search


strsearch.java
// Searching for a String - Linear Search
import java.util.Scanner;
class strsearch
{
public static void main(String args[])throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter How many Strings ?");
int n = sc.nextInt();
int i,j;
String str[ ] = new String[n];
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

for(i=0;i<n;i++)
{
System.out.print("Enter a String:");
str[i]=sc.next();
}
System.out.println("Enter String to be Search :");
String search = sc.next(); ;
boolean found =false;
for(i=0;i<n;i++)
{
if(search.equalsIgnoreCase(str[i]))
{
System.out.println("Found at Position : "+(i+1));
found = true;
}
}
if(!found)
System.out.print("Not Found in the Group");
}
}
Compile and Execute:
D:\CARE JAVA >javac strsearch.java
D:\CARE JAVA >java strsearch
Enter How many Strings?
4
Enter a String:Sathish
Enter a String:Priya
Enter a String:Manoj
Enter a String:Dinesh
Enter String to be Search :
Dinesh
Found at Position:4

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

D:\CARE JAVA >java strsearch


Enter How many Strings?
2
Enter a String:Rahul
Enter a String:Cadad
Enter String to be Search:
RAHUL
Found at Position:1

D:\CARE JAVA >java strsearch


Enter String to be Search:
Gokul
Not Found in the Group

11.8 Ordering of Strings:


//compareTo() and compareToIgnoreCase()
// compareTo()
class alphacmp
{
public static void main(String args[])
{
String name[]={"Kolkatta","Mumbai","Hyderabad","Chennai","Amehadabad",
"Kanpur","Lucknow","bengaluru","delhi","orissa","Srinagar"};
int size = name.length;
int i,j;
String temp = null;
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


if(name[j].compareTo(name[i])<0)
{
temp = name[i];
name[i]=name[j];
name[j]=temp;
}
}

//Output with Difference

}
for(i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}

Compile and Execute:


D:\CARE JAVA >javac alphacmp.java
D:\CARE JAVA >java alphacmp
Using : CompareTo() :
Amehadabad
Chennai
Hyderabad
Kanpur
Kolkatta
Lucknow
Mumbai
Srinagar
bengaluru
delhi
Orissa
//compareToIgnoreCase()
class alphaignore
{
public static void main(String args[])
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


{
String name[]={"Kolkatta","Mumbai","Hyderabad","Chennai","Amehadabad",
"Kanpur","Lucknow","bengaluru","delhi","orissa","Srinagar"};
int size = name.length;
int i,j;
String temp = null;
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(name[j].compareToIgnoreCase(name[i])<0)
{
temp = name[i];
name[i]=name[j];
name[j]=temp;
}
}

// Ignore the Case Difference

}
for(i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}

Compile and Execute:


D:\CARE JAVA>javac alphaignore.java
D:\CARE JAVA >java alphaignore
Using : CompareToIgnoreCase() :
Amehadabad
bengaluru
Chennai
delhi
Hyderabad
Kanpur
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Kolkatta
Lucknow
Mumbai
orissa
Srinagar

12. STRINGBUFFER AND STRINGBUILDER


What is the difference between String and String Buffer Classes?
String class objects are immutable and hence their contents cant be modified. String
Buffer class objects are mutable, so they can be modified. Moreover the methods that directly
manipulate data of the object arent available in String class. Such methods are available in
StringBuffer class.
Creating a StringBuffer

There are two ways to create a StringBuffer Object, and fill the object with a String:
We can create a StringBuffer object by using new operator and pass the string to the
object, as :
StringBuffer sb = new StringBuffer(Hello);
Here, we are passing the string Hello to the StringBuffer object sb.So, a statement

like:
System.out.println(sb);
will display Hello.
StringBuffer sb = new StringBuffer();

Another way of creating a StringBufferobject is to first allotting memory to the


StringBuffer object using new operator and later storing the string into it ,as :
StringBuffer sb = new StringBuffer();

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Here,We are creating a StringBuffer object as an empty object and not passing any string
to it.In this case, a StringBuffer object will be created with a default capacity of 16
characters.
StringBuffer sb = new StringBuffer(20);
Here, StringBuffer object is created as an empty object with a capacity for
storing 20 characters.Of course,even if we declare the capacity as 20,it is possible to store
more than 20 characters into this StringBuffer. The reason is that StringBuffer is
mutuable and can expand dynamically in memory.To store characters,we can use
append() method or insert() methods, as :
sb.append(Hello); //add Hello to sb
sb.insert(0,Hello); //insert Hello starting from 0th position in sb.
12.1 String Buffer Class Methods
There are some methods in StringBuffer class as given here:

StringBuffer append():
StringBuffer insert():
StringBuffer delete():
StringBuffer reverse():
String toString():
int length():
int lastIndexOf():
StringBuffer replace():
String substring():

StringBuffer append(x);
x may be boolean,byte,int,long,float,double,char,character array,String or another
StringBuffer.It will be added to the StringBuffer object. For example,
StringBuffer sb = new StringBuffer(uni);
sb.append(versity);
Preceding two statement produce, University as the string versity is added at the end
of Uni.
StringBuffer sb = new StringBuffer(Intelligent Person);
sb.insert(11,young);
Here, StringBuffer object sb contains Intelligent Person.Counting from 0,we find the
string,intelligent has 10 characters.So, sb .insert(11,young) will insert the string,young at
11th position, and hence we get Intelligent young Person in sb.

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

StringBuffer delete(int i,int j);

This removes the characters from ith position till j -1th position in the StringBuffer.
For Example,
StringBuffer sb =new StringBuffer(university);
sb.delete(0,3);
Here, it deletes the characters from the beginning to 2nd Character (Uni) and the
resultant string in sb will be versity.

int indexOf(String str):


This returns the first occurrence of substring str in the StringBufferObject.For
Example,

int lastIndexOf(String str):


This returns the first occurrence of substring str in the StringBufferObject.
For Example:

StringBuffer replace(int i,int j,String str):


String substring(String str):
String substring(int i,int j):

Program to use some of the StringBuffer class Methods:


//To Compose Full name of a Person
import java.io.*;
import java.util.Scanner;
class stringegbuff1
{
public static void main(String args[])throws IOException
{
//Create Empty String Buffer Object
StringBuffer sb = new StringBuffer();
//To Accept data from Keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter Surname");
String sur =sc.next();
System.out.println("Enter Middleame");
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


String mid =sc.next();
System.out.println("Enter Lastname");
String last =sc.next();
sb.append(sur);
sb.append(last);
System.out.println("Name="+sb);
int n = sur.length();
sb.insert(n,mid);
System.out.println("Full Name = " + sb);
System.out.println("In Reverse = " + sb.reverse());
}
}
Compile and Execute:
D:\CARE JAVA>javac stringegbuff1.java
D:\CARE JAVA>java stringegbuff1
Enter Surname
Sachin
Enter Middleame
Ramesh
Enter Lastname
Tendulkar
Name=SachinTendulkar
Full Name = SachinRameshTendulkar
In Reverse = rakludneThsemaRnihcaS
STRING REVERSE
//How to reverse a String in JAVA Program. (2 Methods).
//Method - I
//Reverse string using StringBuffer class in reverse()
class strgrevs
{
public static void main(String args[])
{
StringBuffer a = new StringBuffer("Java programming is fun");
System.out.println(a.reverse());
}
}
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

Compile and Execute:


D:\CARE JAVA>javac strgrevs.java
D:\CARE JAVA>java strgrevs
nuf si gnimmargorp avaJ
Do Yourself:
//Method - II
//Reverse a String at Runtime in logically
import java.util.*;
class strgreverse
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
}
}
Compile and Execute:
D:\CARE JAVA>javac strgreverse.java
D:\CARE JAVA>java strgreverse
Enter a string to reverse: VIJEY
Reverse of entered string is: YEJIV

Do Yourself:
Testing a String Whether its Palindrome or not.
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

//Testing a Palindrome or Not


import java.util.*;
class stringegbuff2
{
public static void main(String args[])
{
//Accept the String from Keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String :");
String str = sc.next();
//Store a copy of Original String Temp
String temp = str;
StringBuffer sb = new StringBuffer(str);
sb.reverse();
str=sb.toString();
if(temp.equalsIgnoreCase(str))
System.out.println("The Given Word is : " + temp + " . " + str + " and it's a
Palindrome.");
else
System.out.println("The Given Word is : " + temp + " . " + str + " and it's n't a
Palindrome.");
}
}
Compile and Execute:
D:\CARE JAVA>javac stringegbuff2.java
D:\CARE JAVA>java stringegbuff2
Enter a String:
Madam
The Given Word is : Madam. madaM and it's a Palindrome.
12.3 String Builder Class Methods

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


The following are the important methods in StringBuilder class, which are functionally
similar to methods of StringBuffer class discussed previously:

StringBuilder append(x)
StringBuilder insert(int i,x)
StringBuilder delete()
StringBuilder(int i,int j)
StringBuilder reverse()
String toString()
int length()
int indexOf(String str)
int lastindexOf(String str)
StringBuilder replace(int i,int j,String str)
String substring(int i)
String substring(int i,int j)

What is the difference between StringBuffer and StringBuilder classes?


StringBuffer class is synchronized and StringBuilder is not.When the Programmer wants
to use several threads, he should use StringBuffer as it gives reliable results. If only one thread is
used,StringBuilder is preferred,as it improves execution time.
13. ABOUT IDE
A JAVA IDE
A Java IDE (Integrated Development Environment) is a software application which
enables users to more easily write and debug Java programs. Many IDEs provide features like
syntax highlighting and code completion, which help the user to code more easily.
Here is a useful list of Java IDEs. They are in NO specific order!

ECLIPSE
NETBEANS
JCREATOR
INTELLIJ IDEA
BORLAND JBUILDER
DR. JAVA
BLUEJ

ECLIPSE
This is a very good and open source IDE. It is used a lot commercially and personally. It
was made in Java so it's cross-platform. It has a lot of support for additional plug-ins to extend
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


your developing needs. What I love about Eclipse is that it compiles your code as you type. It
highlights compiling errors and mistakes like how MS Word does for mis-spelled words.
NETBEANS
This is a very good IDE also. It has a built-in GUI Builder for those you like that R.A.D. .
It is used a lot commercially too. It was made in Java so it's cross-platform like Eclipse.

JCREATOR

This is my first Java IDE I used. It is very good and very easy to use. This IDE was made
in C++ unlike the ones above, which were all made in Java. Only runs on Windows platform.

INTELLIJ IDEA

IntelliJ IDEA is an intelligent Java IDE intensely focused on developer productivity that
provides a robust combination of enhanced development tools.

BORLAND JBUILDER

This is a great commerial IDE for Java. It does have a price but some developers believe
it's worth it. It also has a built-in Java GUI Builder.

DR. JAVA

Dr. Java is a lightweight development environment for writing Java programs. It is


designed primarily for students, providing an intuitive interface and the ability to interactively
evaluate Java code. It also includes powerful features for more advanced users.

BLUEJ

This is an IDE developed towards first time Java developers. It teaches you a lot of
programming concepts in Java and has a nice UML tool.

14. INTRODUCTION TO OOPS


14.1 FEATURES OF OOPS

14.2 DIFFERENCE BETWEEN OBJECT ORIENTED PROGRAMMING LANGUAGES


AND OBJECT BASED ORIENTED PROGRAMMING LANGUAGES

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

14.3 CLASSES AND OBJECTS


OBJECT AND CLASS IN JAVA
In this page, we will learn about java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
OBJECT IN JAVA:
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car
etc. It can be physical or logical (tengible and intengible). The example of integible object is
banking system.
An object has three characteristics:

state: represents data (value) of an object.

behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.

identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But,it is used internally by the JVM to identify each object
uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behaviour.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance (result) of a class.

CLASS IN JAVA:
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


A class in java can contain:

data member
method
constructor
block
class and interface

Syntax to declare a class:


class <class_name>
{
data member;
method;
}
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing the objects
value.
Student1.java
class Student1
{
int id;

//data member (also instance variable)

String name;

//data member(also instance variable)

public static void main(String args[])


{
Student1 s1=new Student1();

//creating an object of Student

System.out.println(s1.id);
System.out.println(s1.name);
}
}

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


Output:
0 null
Student2.java
class Student2
{
int id = 10;

//data member (also instance variable)

String name="Hari';

//data member(also instance variable)

public static void main(String args[])


{
Student1 s1=new Student1();

//creating an object of Student

System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
10
Hari
Demo1.java
// If we didn;t pass the value of obj.name and obj.regno on Demo1 class, it could be null
and 0.
class person
{
int regno;
String name;
void talk()
{
System.out.println("My Reg. No :" + regno);
System.out.println("My Name is :" + name);
}
}
class Demo1
{

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


public static void main(String args[])
{
person obj = new person();
obj.regno = 21;
obj.name = "Vignesh";
obj.talk();
}
}
Output:
My Reg. No : 21
My Name is : Vignesh
Demo2.java
//We pass the Value on Person class and Call the Method on main class(Demo2).
class person
{
//Instance Variables
String name="Jackson";
int age=24;
void talk()
{
System.out.println("Hello I am :" + name);
System.out.println("My age is :" + age);
}
}
class Demo2
{
public static void main(String args[])
{
person obj = new person();
obj.talk();
}
}

//Rule for creating a Object

Output:
Hello I am : Jackson
My age is : 24
Demo3.java
// To initialise the instance variables directly with in private Access Specifiers.
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

class person
{
//Instance Variables
private String name="Janani";
private int mark=90;
void talk()
{
System.out.println("Hello I am :" + name);
System.out.println("My Mark is :" + mark);
}
}
class Demo3
{
public static void main(String args[])
{
person obj1 = new person();
obj1.talk();
person obj2 = new person();
obj2.talk();
}
}
Output:
Hello I am : Janani
My Mark is :90
Hello I am Janani
My Mark is: 90
15. ACCESS SPECIFIERS
An access specifier is a key word that specifies how to access the members of a class or a
class itself. We can use access specifier before a class and its members. There are four access
specifiers available in java:
private,public, protected and default.
15.1 Programs for initialize the instance variables directly within class
16. CONSTRUCTOR AND ITS TYPES
CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming

A constructor is similar to a method that is used to initialize the instance variables.


The purpose of a constructor is to initialize the instance variables. A constructor has the
following characteristics:
The constructors name and class name should be same.And the constructors name
should end with a pair of simple braces.
For Eg: In a person class , We can write a constructor as :

person()
{
}
A constructor may have or may not have parameters. Parameters are variables to receive
data from outside into the constructor. If a constructor has 1 or more parameters, its
called Parameterized Constructor. For Eg, We can write a default constructor as :
person()
{
}

And a parameterized constructor with two parameters ,as :


person(int i,Stirng str)
{
}

A constructor does not return any value, not even void. Recollect, if a method
does not return any value, we shouldnt even write void before the constructor.

A constructor is automatically called and executed at the time of creating an


object. While creating an object, if nothing is passed to the object, then the parameterized
constructor is called. For Eg,if we create the object as :

o person Raju = new person();


//Here default constructor
o person Raju = new person(Raju,22);
//Here parameterized
constructor will receive Raju and 22.
A constructor is called and executed only once per object. This means when we create an
object, the constructor is called. When we create second object,again the constructor is
called second time.

IQs:

16.1 Initializing a Variables using a default constructor

CARE GROUP OF INSTITUTIONS

CPDP-JAVA (2016-2017) JAVA Programming


16.2 Initializing a Variables using a Parameterized constructor
16.3 Difference between default and parameterized constructor
16.3 Difference between Constructors and Methods

CARE GROUP OF INSTITUTIONS

You might also like