Java Programs
Java Programs
Example
d:> javac first.java
Example
d:>java sample
display.java:
import java.io.*;
class display
{
public staic void main(String args[])
{
System.out.println(Welcome to JAVA);
}
}
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! ! !");
!!!
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[])
{
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
Relational Operator
Logical Operator
Boolean Operator
Bitwise Operators
Ternary or Conditional Operators
//250.0
//0
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)
DESCRIPTION
&
Bitwise or operator
<<
>>
>>>
Bitwiseand.java
class Bitwiseand
{
public static void main (String args[])
{
}
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);
}
}
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
//11=0000
//-12
//44
//2
//2
//1
//1
}
}
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
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
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
Objectname.variablename
;
emp.id
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()
Objectname.methodname
br.read()
instanceof Operator:
Example
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
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;
case 'g':
case 'G':
System.out.println("Green");
break;
case 'b':
case 'B':
System.out.println("Blue");
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
//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
}
}
Cycle-III num=0
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.
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
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
Keyboard
First, we should accept the integer number from the keyboard as a String.Using
readLine() as :
String str = 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
Similarly, We can write different statements to accept many other data types from keyboard as
follows :
byte b = Byte.parseByte(br.readLine());
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 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
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:
sorting.java
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
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};
stringeg3.java
class stringeg3
{
public static void main(String args[])
{
CARE GROUP OF INSTITUTIONS
//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
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
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
{
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
}
for(i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}
}
for(i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}
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();
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.
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.
Do Yourself:
Testing a String Whether its Palindrome or not.
CARE GROUP OF INSTITUTIONS
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)
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
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
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.
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.
data member
method
constructor
block
class and interface
String name;
System.out.println(s1.id);
System.out.println(s1.name);
}
}
String name="Hari';
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
{
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
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
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()
{
}
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.
IQs: