SlideShare a Scribd company logo
1 | P a g e
EX: 1 // HELLO WORLD
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Output of program:
EX:2 // If else in Java code
import java.util.Scanner;
class IfElse {
public static void main(String[] args) {
int marksObtained, passingMarks;
passingMarks = 40;
Scanner input = new
Scanner(System.in);
System.out.println("Input marks scored
by you");
marksObtained = input.nextInt();
if (marksObtained >= passingMarks) {
System.out.println("You passed the
exam.");
}
else {
System.out.println("Unfortunately you
failed to pass the exam.");
}
}
}
Output of program:
EX:3 // Nested If else in Java code
import java.util.Scanner;
class NestedIfElse {
public static void main(String[] args) {
int marksObtained, passingMarks;
char grade;
passingMarks = 40;
Scanner input = new
Scanner(System.in);
System.out.println("Input marks scored
by you");
2 | P a g e
marksObtained = input.nextInt();
if (marksObtained >= passingMarks) {
if (marksObtained > 90)
grade = 'A';
else if (marksObtained > 75)
grade = 'B';
else if (marksObtained > 60)
grade = 'C';
else
grade = 'D';
System.out.println("You passed the
exam and your grade is " + grade);
}
else {
grade = 'F';
System.out.println("You failed and your
grade is " + grade);
}
}
}
Java for loop syntax
for (/* Initialization of variables */ ;
/*Conditions to test*/ ; /* Increment(s) or
decrement(s) of variables */)
{
// Statements to execute i.e. Body of for
loop
}
Ex:4 // Infinite for loop
for (;;) {
System.out.println("Java programmer");
}
Ex: 5 program below uses for loop to
print first 10 natural numbers i.e. from 1
to 10.
//Java for loop program
class ForLoop {
public static void main(String[] args) {
int c;
for (c = 1; c <= 10; c++) {
System.out.println(c);
}
}
}
Output of program:
Ex:6Java for loop example to print stars in
console
Following star pattern is printed
*
**
***
****
*****
class Stars {
public static void main(String[] args) {
int row, numberOfStars;
for (row = 1; row <= 10; row++) {
3 | P a g e
for(numberOfStars = 1; numberOfStars
<= row; numberOfStars++) {
System.out.print("*");
}
System.out.println(); // Go to next line
}
}
}
Output of program:
JAVA WHILE LOOP
while loop syntax:
while (condition(s))
{
// Body of loop
}
1. If the condition holds true then the
body of loop is executed, after execution
of loop body condition is tested again
and if the condition is true then body of
loop is executed again and the process
repeats until condition becomes false.
Condition is always evaluated to true or
false and if it is a constant, For example
while (c) { …} where c is a constant then
any non zero value of c is considered
true and zero is considered false.
2. You can test multiple conditions such
as
while ( a > b && c != 0) {
// Loop body
}
Loop body is executed till value of a is
greater than value of b and c is not
equal to zero.
3. Body of loop can contain more than
one statement. For multiple statements
you need to place them in a block using
{} and if body of loop contain only single
statement you can optionally use {}. It is
recommended to use braces always to
make your program easily readable and
understandable.
EX: 7 program asks the user to input an
integer and prints it until user enter 0
(zero).
import java.util.Scanner;
class WhileLoop {
public static void main(String[] args) {
int n;
Scanner input = new
Scanner(System.in);
System.out.println("Input an integer");
while ((n = input.nextInt()) != 0) {
System.out.println("You entered " + n);
System.out.println("Input an integer");
}
System.out.println("Out of loop");
}
}
4 | P a g e
Output of program:
Ex:8 // Printing alphabets
class Alphabets
{
public static void main(String args[])
{
char ch;
for( ch = 'a' ; ch <= 'z' ; ch++ )
System.out.println(ch);
}
}
You can easily modify the above java
program to print alphabets in upper
case.output of program:
Printing alphabets using while loop (only
body of main method is shown):
char c = 'a';
while (c <= 'z') {
System.out.println(c);
c++;
}
Using do while loop:
char c = 'A';
do {
System.out.println(c);
c++;
} while (c <= 'Z');
Ex: 9 // program for multiplication table
import java.util.Scanner;
class MultiplicationTable
{
public static void main(String args[])
{
int n, c;
System.out.println("Enter an integer to
print it's multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication
table of "+n+" is :-");
for ( c = 1 ; c <= 10 ; c++ )
System.out.println(n+"*"+c+" =
"+(n*c));
}
}
5 | P a g e
Output of program:
Retrieving input from the user
Scanner a = new Scanner(System.in);
Here Scanner is the class name, a is the
name of object, new keyword is used to
allocate the memory and System.in is
the input stream. Following methods of
Scanner class are used in the program
below :-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
Ex:10
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string
"+s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered
integer "+a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float
"+b);
}
}
Output of program:
Ex:11
import java.util.Scanner;
class AddNumbers
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter two integers
to calculate their sum ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = x + y;
System.out.println("Sum of entered
integers = "+z);
}
}
6 | P a g e
Output of program:
Ex:12
import java.util.Scanner;
class OddOrEven
{
public static void main(String args[])
{
int x;
System.out.println("Enter an integer to
check if it is odd or even ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if ( x % 2 == 0 )
System.out.println("You entered an
even number.");
else
System.out.println("You entered an
odd number.");
}
}
Output of program:
Ex:13 Another method to check odd or
even
import java.util.Scanner;
class EvenOdd
{
public static void main(String args[])
{
int c;
System.out.println("Input an integer");
Scanner in = new Scanner(System.in);
c = in.nextInt();
if ( (c/2)*2 == c )
System.out.println("Even");
else
System.out.println("Odd");
}
}
EX:15 //Fahrenheit to Celsius
import java.util.*;
class FahrenheitToCelsius {
public static void main(String[] args) {
float temperatue;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperatue in
Fahrenheit");
temperatue = in.nextInt();
temperatue = ((temperatue - 32)*5)/9;
System.out.println("Temperatue in
Celsius = " + temperatue);
}
}
7 | P a g e
Output of program:
[ For Celsius to Fahrenheit conversion
use
T = 9*T/5 + 32
where T is temperature on Celsius
scale.]
** Create and test Fahrenheit to Celsius
program yourself for practice.
Java methods
Java program consists of one or more
classes and a class may contain
method(s).
A class can do very little without
methods.
A method has a name and return type.
Main method is a must in a Java
program as execution begins from it.
Syntax of methods
"Access specifier" "Keyword(s)" "return
type" methodName(List of arguments)
{
// Body of method
}
Access specifier can be public or private
which decides whether other classes can
call a method.
Keywords are used for some special
methods such as static or synchronized.
Return type indicate return value which
method returns.
Method name is a valid Java identifier
name.
 Access specifier, Keyword and
arguments are optional.
Examples of methods declaration:
public static void main(String[] args);
void myMethod();
private int maximum();
public synchronized int
search(java.lang.Object);
Ex:16
class Methods
{
// Constructor method
Methods()
{
System.out.println("Constructor method
is called when an object of it's class is
created");
}
// Main method where program
execution begins
public static void main(String[] args)
{
staticMethod();
Methods object = new Methods();
object.nonStaticMethod();
}
// Static method
static void staticMethod()
{
System.out.println("Static method can be
called without creating object");
8 | P a g e
}
// Non static method
void nonStaticMethod()
{
System.out.println("Non static method
must be called by creating an object");
}
}
Output of program:
Java methods list
Java has a built in library of many useful
classes and there are thousands of
methods which can be used in your
programs.
javap package.classname
For example
javap java.lang.String // list all methods
and constants of String class.
javap java.math.BigInteger // list
constants and methods of BigInteger
class in java.math package
Java String methods
String class contains methods which are
useful for performing operations on
String(s). Below program illustrate how
to use inbuilt methods of String class.
Java string class program
EX:15
class StringMethods
{
public static void main(String args[])
{
int n;
String s = "Java programming", t = "", u =
"";
System.out.println(s);
// Find length of string
n = s.length();
System.out.println("Number of
characters = " + n);
// Replace characters in string
t = s.replace("Java", "C++");
System.out.println(s);
System.out.println(t);
// Concatenating string with another
string
u = s.concat(" is fun");
System.out.println(s);
System.out.println(u);
}
}
Output of program:
Ex:16 Array input at run time
import java.io.*;
import java.util.Scanner;
class arrayruntime
{
public static void main(String args[])
{
Scanner a =new Scanner(System.in);
int a1[] = new int[5];
int j= a1.length;
9 | P a g e
for(int i=0;i<j;i++)
{
int k= a.nextInt();
a1[i]=k;
}
for(int i=0;i<j;i++)
{
System.out.println(a1[i]);
}
}
}
Output
Java arrayruntime
45
45
57
35
29
45
45
57
35
29
Ex:17 Sorting odd and even
import java.io.*;
import java.util.Scanner;
class arrayruntimeoddeven
{
public static void main(String args[])
{
Scanner a =new Scanner(System.in);
int a1[] = new int[5];
int j= a1.length;
for(int i=0;i<j;i++)
{
int k= a.nextInt();
a1[i]=k;
}
System.out.println("The array is");
for(int i=0;i<j;i++)
{
System.out.println(a1[i]);
}
for(int i=0;i<j;i++)
{
if(a1[i]%2==0)
{
int l = a1[i];
System.out.println(l+" is even");
}
else
{
int l = a1[i];
System.out.println(l+" is odd");
}
}
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java
arrayruntimeoddeven
23
33
54
32
78
The array is
23
33
54
32
78
23 is odd
33 is odd
54 is even
32 is even
78 is even
10 | P a g e
Ex:18 Constructor
class area
{
int length;
int breadth;
area ( int a, int b)//constructor
{
length =a;
breadth =b;
}
int rectarea()
{
int area2 =length*breadth;
return area2;
}
}
class constructor
{
public static void main(String args[])
{
int area1;
area a1 = new area(12,15);
//a1.getdata(12,15);
area1 = a1.rectarea();
System.out.println("area is "+area1);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java
constructor
area is 180
Ex:19 getinput during execution
class get
{
public static void main(String args[])
{
int a= Integer.parseInt(args[0]);
System.out.println(a);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java get 2
2
Ex:20 Get user input at runtime using
bufferedreader
import java.io.*;
public class getuserinput
{
public static void main (String[] args)
{
System.out.print("Enter your name and
press Enter: ");
BufferedReader br = new
BufferedReader(new
InputStreamReader(System.in));
String name = null;
try
{
name = br.readLine();
}
catch (IOException e)
{
System.out.println("Error!");
System.exit(1);
}
System.out.println("Your name is " +
name);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
getuserinput.java
C:Program
FilesJavajdk1.6.0_13bin>java
getuserinput
Enter your name and press Enter:
sudharsun
Your name is sudharsun
11 | P a g e
Ex:21 Inheritance
class Room
{
int length;
int breadth;
Room (int x,int y)
{
length =x;
breadth=y;
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x,int y, int z)
{
super(x,y);
height =z;
}
int volume()
{
return(length*breadth*height);
}
}
class inheritance
{
public static void main(String args[])
{
BedRoom r1= new BedRoom(2,4,5);
int vol = r1.volume();
System.out.println(vol);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
inheritance.java
C:Program
FilesJavajdk1.6.0_13bin>java
inheritance
40
Ex:22 Get input using data input stream
import java .io.DataInputStream;
class input
{
public static void main(String args[])
{
DataInputStream in = new
DataInputStream(System.in);
int i=0;
try
{
i=Integer.parseInt(in.readLine());
}
catch (Exception e)
{
}
System.out.println(i);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java input
23
23
Ex:23 Overloading
class area
{
int length;
int breadth;
area(int x,int y) /*using constructor*/
{
length= x;
breadth= y;
}
area(int x) /*using constructor*/
{
length=breadth=x;
}
int area1()
{
return(length*breadth);
}
12 | P a g e
}
class overload
{
public static void main(String args[])
{
area r1 = new area(2,3);/*calling
Constructor*/
area r2 = new area(3);
int a1 = r1.area1();
int a2 = r2.area1();
System.out.println(a1);
System.out.println(a2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
overload.java
C:Program
FilesJavajdk1.6.0_13bin>java overload
6
9
Ex:24 Overload program 2 input at
runtime
class room
{
int length;
int breadth;
room(int x,int y)
{
length= x;
breadth= y;
}
room(int x)
{
length=breadth=x;
}
int area()
{
return(length*breadth);
}
}
class overload1
{
public static void main(String args[])
{
int i= Integer.parseInt(args[0]);
int j= Integer.parseInt(args[1]);
room r1 = new room(i,j);
int k= Integer.parseInt(args[2]);
room r2 = new room(k);
int area1 = r1.area();
int area2 = r2.area();
System.out.println(area1);
System.out.println(area2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java overload1
101 101 12
10201
144
Ex:25 Overriding
class superclass
{
int x;
superclass(int x)
{
this.x=x;
}
void display()
{
System.out.println(x);
}
}
class subclass extends superclass
{
int y;
subclass(int x , int y)
{
super(x);
this.y=y;
}
void display()
{
13 | P a g e
System.out.println(y);
}
}
class overriding
{
public static void main(String args[])
{
subclass s1=new subclass(100,200);
s1.display();
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
overriding.java
C:Program
FilesJavajdk1.6.0_13bin>java overriding
200
Ex:26 Replace a letter in a word
class replace
{
public static void main(String args[])
{
String s1= "Hello";
System.out.println(s1);
String s2 = s1.replaceFirst("lo","p");
System.out.println(s2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java replace
Hello
Help
Ex:27 Sample program for java
class area
{
int length;//
int breadth;//Field Decl
void getdata( int a, int b)//Method Decl
{
length =a;
breadth =b;
}
int rectarea()
{
int area =length*breadth;
return area;
}
}
class sample
{
public static void main(String args[])
{
int area1;
area a1 = new area();
a1.getdata(12,15);
area1 = a1.rectarea();
System.out.println("area is "+area1);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
sample.java
C:Program
FilesJavajdk1.6.0_13bin>java sample
area is 180
Ex:28 get user input using scanner
import java.io.*;
import java.util.Scanner;
public class scanner
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String i;
i=in.nextLine();
// String i= next();// Does not read spaces
//int i= nextInt();// read integer and for
float and double add them int the palce of
next"Int"
14 | P a g e
System.out.println(i);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
scanner.java
C:Program
FilesJavajdk1.6.0_13bin>java scanner
10
10
Ex:29 Display of substring
class str1
{
public static void main(String args[])
{
String s1 ="hello";
String s2 ="hello";
System.out.println(s1.substring(0,2)+"lp");
char s3 = s1.charAt(3);
System.out.println(s3);
if (s1.equals(s2))
{
System.out.println("true");
}
else
{
System.out.println("false");
}
String s4 =s1.substring(0,2);
System.out.println(s4);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java str1
help
l
true
he
Ex:30 call of an function
class functioncall
{
public static void funct1 ()
{
System.out.println ("Inside funct1");
}
public static int funct2 (int param)
{
System.out.println ("Inside funct2 with
param " + param);
return param * 2;
}
public static void main (String[] args)
{
int val;
System.out.println ("Inside main");
funct1();
System.out.println ("About to call funct2");
val = funct2(8);
System.out.println ("funct2 returned a
value of " + val);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
functioncall.java
C:Program
FilesJavajdk1.6.0_13bin>java
functioncall
Inside main
Inside funct1
About to call funct2
Inside funct2 with param 8
funct2 returned a value of 16
Ex:31 display the current date
15 | P a g e
import java.util.*;
class hellodate
{
public static void main (String[] args)
{
System.out.println ("Hello, it's: ");
System.out.println(new Date());
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
hellodate.java
C:Program
FilesJavajdk1.6.0_13bin>java hellodate
Hello, it's:
Thu Sep 29 11:05:16 GMT+05:30 2011
Ex:32 Lab program (rational number)
import java.io.*;
import java.util.Scanner;
public class rational
{
public static void main(String args[])
{
System.out.println("The give required
Numbers ");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int i;
System.out.println("The given rational
Number is");
System.out.println(a+"/"+b);
if(a<b)
{
for(i=2;i<=9;i++)
{
while(a%i==0 && b%i==0)
{
a=a/i;
b=b/i;
}
}
}
else
{
for(i=2;i<=9;i++)
{
while(a%i==0 && b%i==0)
{
a=a/i;
b=b/i;
}
}
}
System.out.println("The simplified rational
number is");
System.out.println(a+"/"+b);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
rational.java
C:Program
FilesJavajdk1.6.0_13bin>java rational
The give required Numbers
3
54
The given rational Number is
3/54
The simplified rational number is
1/18
Ex:33 Reverse an number eg 10 01
public class ReverseNumber
{
public static void main(String[] args)
{
int number = 1234;
int reversedNumber = 0;
int temp = 0;
while(number > 0)
{
temp = number%10;
reversedNumber = reversedNumber * 10 +
temp;
16 | P a g e
number = number/10;
}
System.out.println("Reversed Number is: "
+ reversedNumber);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
ReverseNumber.java
C:Program
FilesJavajdk1.6.0_13bin>java
ReverseNumber
Reversed Number is: 4321
Ex:34 Swap function call eg a=5 b=6 a=6
b=5
public class swap
{
public static void main(String[] args)
{
int num1 = 10;
int num2 = 20;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" +
num1);
System.out.println("Value of num2 is :"
+num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" +
num1);
System.out.println("Value of num2 is :"
+num2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
swap.java
C:Program
FilesJavajdk1.6.0_13bin>java swap
Before Swapping
Value of num1 is :10
Value of num2 is :20
Before Swapping
Value of num1 is :20
Value of num2 is :10
Ex:35 Program to compare string
import java.util.Scanner;
class Compare_Strings
{
public static void main(String args[])
{
String s1, s2;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
s1 = in.nextLine();
System.out.println("Enter the second
string");
s2 = in.nextLine();
if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater
than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller
than second.");
else
System.out.println("Both strings are
equal.");
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
Compare_Strings.java
17 | P a g e
C:Program
FilesJavajdk1.6.0_13bin>java
Compare_Strings
Enter the first string
sun
Enter the second string
sun
Both strings are equal.
Ex:36 Sorting string in an array
import java.util.Arrays;
public class ArrayStringSorting {
public static void main(String[] args) {
String[] arrayList = new String[] {
"Thirumal", "Banana", "Apple", "Pears",
"Orange" };
System.out.println("Before sorting the
array: " + Arrays.asList(arrayList));
Arrays.sort(arrayList); // sort method used
to sort the array contents .
System.out.println("After sorting the
array: " + Arrays.asList(arrayList));
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java
ArrayStringSorting
Before sorting the array: [Thirumal,
Banana, Apple, Pears, Orange]
After sorting the array: [Apple, Banana,
Orange, Pears, Thirumal]
Ex:37 Program to change the colour of
the background
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* @version 1.33 2007-06-12
* @author Cay Horstmann
*/
public class ActionTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
ActionFrame frame = new ActionFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* A frame with a panel that demonstrates
color change actions.
*/
class ActionFrame extends JFrame
{
public ActionFrame()
{
setTitle("ActionTest");
setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
buttonPanel = new JPanel();
// define actions
Action yellowAction = new
ColorAction("Yellow", new
ImageIcon("yellow-
ball.gif"),Color.YELLOW);
Action blueAction = new
ColorAction("Blue", new ImageIcon("blue-
ball.gif"), Color.BLUE);
Action redAction = new ColorAction("Red",
new ImageIcon("red-ball.gif"), Color.RED);
// add buttons for these actions
18 | P a g e
buttonPanel.add(new
JButton(yellowAction));
buttonPanel.add(new
JButton(blueAction));
buttonPanel.add(new JButton(redAction));
// add panel to frame
add(buttonPanel);
// associate the Y, B, and R keys with
names
InputMap imap =
buttonPanel.getInputMap(JComponent.W
HEN_ANCESTOR_OF_FOCUSED_COMPONE
NT);
imap.put(KeyStroke.getKeyStroke("ctrl Y"),
"panel.yellow");
imap.put(KeyStroke.getKeyStroke("ctrl B"),
"panel.blue");
imap.put(KeyStroke.getKeyStroke("ctrl R"),
"panel.red");
// associate the names with actions
ActionMap amap =
buttonPanel.getActionMap();
amap.put("panel.yellow", yellowAction);
amap.put("panel.blue", blueAction);
amap.put("panel.red", redAction);
}
public class ColorAction extends
AbstractAction
{
/**
* Constructs a color action.
* @param name the name to show on the
button
* @param icon the icon to display on the
button
* @param c the background color
*/
public ColorAction(String name, Icon icon,
Color c)
{
putValue(Action.NAME, name);
putValue(Action.SMALL_ICON, icon);
putValue(Action.SHORT_DESCRIPTION,
"Set panel color to " +
name.toUpperCase());
putValue("color", c);
}
public void actionPerformed(ActionEvent
event)
{
Color c = (Color) getValue("color");
buttonPanel.setBackground(c);
}
}
private JPanel buttonPanel;
public static final int DEFAULT_WIDTH =
300;
public static final int DEFAULT_HEIGHT =
200;
}
Ex:38 Testing the button
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
19 | P a g e
}
});
}
}
@SuppressWarnings("serial")
class ButtonFrame extends JFrame
{
private final static int DEFAULT_WIDTH =
300;
private final static int DEFAULT_HEIGHT =
200;
private final JPanel buttonPanel;
public ButtonFrame()
{
this.setTitle("Button Frame");
this.setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
this.buttonPanel = new JPanel();
PanelButton yellowButton = new
PanelButton("Yellow", Color.YELLOW,
buttonPanel);
PanelButton redButton = new
PanelButton("Red", Color.RED,
buttonPanel);
PanelButton blueButton = new
PanelButton("Blue", Color.BLUE,
buttonPanel);
this.buttonPanel.add(yellowButton);
this.buttonPanel.add(redButton);
this.buttonPanel.add(blueButton);
// add panel to frame
this.add(this.buttonPanel);
}
}
@SuppressWarnings("serial")
class PanelButton extends JButton
implements ActionListener
{
private final Color buttonColor;
private final JPanel buttonPanel;
public PanelButton(String title, Color
buttonColor,
JPanel buttonPanel)
{
super(title);
this.buttonColor = buttonColor;
this.buttonPanel = buttonPanel;
this.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent
event)
{
buttonPanel.setBackground(this.buttonCol
or);
}
}
Ex:39 Mouse event
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.geom.*;
import javax.swing.*;
/**
* @version 1.32 2007-06-12
* @author Cay Horstmann
*/
public class MouseTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MouseFrame frame = new MouseFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
20 | P a g e
}
/**
* A frame containing a panel for testing
mouse operations
*/
class MouseFrame extends JFrame
{
public MouseFrame()
{
setTitle("MouseTest");
setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
// add component to frame
MouseComponent component = new
MouseComponent();
add(component);
}
public static final int DEFAULT_WIDTH =
300;
public static final int DEFAULT_HEIGHT =
200;
}
/**
* A component with mouse operations for
adding and removing squares.
*/
class MouseComponent extends
JComponent
{
public MouseComponent()
{
squares = new ArrayList<Rectangle2D>();
current = null;
addMouseListener(new MouseHandler());
addMouseMotionListener(new
MouseMotionHandler());
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// draw all squares
for (Rectangle2D r : squares)
g2.draw(r);
}
/**
* Finds the first square containing a point.
* @param p a point
* @return the first square that contains p
*/
public Rectangle2D find(Point2D p)
{
for (Rectangle2D r : squares)
{
if (r.contains(p)) return r;
}
return null;
}
/**
* Adds a square to the collection.
* @param p the center of the square
*/
public void add(Point2D p)
{
double x = p.getX();
double y = p.getY();
current = new Rectangle2D.Double(x -
SIDELENGTH / 2, y - SIDELENGTH / 2,
SIDELENGTH,SIDELENGTH);
squares.add(current);
repaint();
}
/**
* Removes a square from the collection.
* @param s the square to remove
*/
public void remove(Rectangle2D s)
{
21 | P a g e
if (s == null) return;
if (s == current) current = null;
squares.remove(s);
repaint();
}
private static final int SIDELENGTH = 10;
private ArrayList<Rectangle2D> squares;
private Rectangle2D current;
// the square containing the mouse cursor
private class MouseHandler extends
MouseAdapter
{
public void mousePressed(MouseEvent
event)
{
// add a new square if the cursor isn't
inside a square
current = find(event.getPoint());
if (current == null) add(event.getPoint());
}
public void mouseClicked(MouseEvent
event)
{
// remove the current square if double
clicked
current = find(event.getPoint());
if (current != null && event.getClickCount()
>= 2) remove(current);
}
}
private class MouseMotionHandler
implements MouseMotionListener
{
public void mouseMoved(MouseEvent
event)
{
// set the mouse cursor to cross hairs if it
is inside
// a rectangle
if (find(event.getPoint()) == null)
setCursor(Cursor.getDefaultCursor());
else
setCursor(Cursor.getPredefinedCursor(Cur
sor.HAND_CURSOR ));
}
public void mouseDragged(MouseEvent
event)
{
if (current != null)
{
int x = event.getX();
int y = event.getY();
// drag the current rectangle to center it at
(x, y)
current.setFrame(x - SIDELENGTH / 2, y -
SIDELENGTH / 2, SIDELENGTH,
SIDELENGTH);
repaint();
}
}
}
}
Implementation of look and feel
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
/**
* @version 1.32 2007-06-12
* @author Cay Horstmann
*/
public class PlafTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
22 | P a g e
public void run()
{
PlafFrame frame = new PlafFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* A frame with a button panel for changing
look and feel
*/
class PlafFrame extends JFrame
{
public PlafFrame()
{
setTitle("PlafTest");
setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
buttonPanel = new JPanel();
UIManager.LookAndFeelInfo[] infos =
UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo info :
infos)
makeButton(info.getName(),
info.getClassName());
add(buttonPanel);
}
/**
* Makes a button to change the pluggable
look and feel.
* @param name the button name
* @param plafName the name of the look
and feel class
*/
void makeButton(String name, final String
plafName)
{
// add button to panel
JButton button = new JButton(name);
buttonPanel.add(button);
// set button action
button.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent
event)
{
// button action: switch to the new look
and feel
try
{
UIManager.setLookAndFeel(plafName);
SwingUtilities.updateComponentTreeUI(Pl
afFrame.this);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
private JPanel buttonPanel;
public static final int DEFAULT_WIDTH =
300;
public static final int DEFAULT_HEIGHT =
200;
}

More Related Content

What's hot

Functional programming
Functional programmingFunctional programming
Functional programming
S M Asaduzzaman
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
Sunil OS
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
KrutikaWankhade1
 
This pointer
This pointerThis pointer
This pointer
Kamal Acharya
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
Shubham Vishwambhar
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
Jayfee Ramos
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Selenium cheat sheet
Selenium cheat sheetSelenium cheat sheet
Selenium cheat sheet
Sri Priya P Kulkarni
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
Abid Kohistani
 
Methods and constructors in java
Methods and constructors in javaMethods and constructors in java
Methods and constructors in java
baabtra.com - No. 1 supplier of quality freshers
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
Richard Walker
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Exception handling
Exception handling Exception handling
Exception handling
M Vishnuvardhan Reddy
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Jorge Vásquez
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
Selenium WebDriver avec Java
Selenium WebDriver avec Java Selenium WebDriver avec Java
Selenium WebDriver avec Java
Ahmed HARRAK
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
Mysql creating stored function
Mysql  creating stored function Mysql  creating stored function
Mysql creating stored function
Prof.Nilesh Magar
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
Ramasubbu .P
 

What's hot (20)

Functional programming
Functional programmingFunctional programming
Functional programming
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
 
This pointer
This pointerThis pointer
This pointer
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Selenium cheat sheet
Selenium cheat sheetSelenium cheat sheet
Selenium cheat sheet
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Methods and constructors in java
Methods and constructors in javaMethods and constructors in java
Methods and constructors in java
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Exception handling
Exception handling Exception handling
Exception handling
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Selenium WebDriver avec Java
Selenium WebDriver avec Java Selenium WebDriver avec Java
Selenium WebDriver avec Java
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Mysql creating stored function
Mysql  creating stored function Mysql  creating stored function
Mysql creating stored function
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 

Viewers also liked

Panorama
PanoramaPanorama
Sistemas operativos 1 bach
Sistemas operativos 1 bachSistemas operativos 1 bach
Sistemas operativos 1 bach
pablolopezmenendez
 
Our Wonderful World! 1# LRC
Our Wonderful World! 1# LRCOur Wonderful World! 1# LRC
Our Wonderful World! 1# LRC
langrenchi
 
Christmas Pompon LRC
Christmas Pompon LRCChristmas Pompon LRC
Christmas Pompon LRC
langrenchi
 
2x360° Panorama (1)
2x360° Panorama (1)2x360° Panorama (1)
2x360° Panorama (1)
langrenchi
 
powerpoint
powerpointpowerpoint
powerpoint
pasxalis
 
Eksterno
EksternoEksterno
тема [автосохраненный] [восстановленный]
тема [автосохраненный] [восстановленный]тема [автосохраненный] [восстановленный]
тема [автосохраненный] [восстановленный]
Tamara Emec
 
критерії
критеріїкритерії
критерії
Tamara Emec
 
Натпревар по математика 2015/2016
Натпревар по математика 2015/2016Натпревар по математика 2015/2016
Натпревар по математика 2015/2016
Violetka Spasevska
 
читання
читаннячитання
читання
Tamara Emec
 
Математика
МатематикаМатематика
Математика
Bilim All
 
математика
математикаматематика
математика
Tamara Emec
 
моите ученици
моите ученицимоите ученици
моите ученици
Violetka Spasevska
 
предлог задачи за подготовка за натпревар
предлог задачи за подготовка за натпреварпредлог задачи за подготовка за натпревар
предлог задачи за подготовка за натпревар
Violetka Spasevska
 
Bor moj grad copy
Bor moj grad   copyBor moj grad   copy
Bor moj grad copy
nadaoliilic
 
Шебер қолдар
Шебер қолдарШебер қолдар
Шебер қолдар
Айбек Қуандықұлы
 
Математика цариця наук
Математика цариця наукМатематика цариця наук
Математика цариця наук
Вова Попович
 
Математика цариця наук (Радовець Н.Я.)
Математика цариця наук (Радовець Н.Я.)Математика цариця наук (Радовець Н.Я.)
Математика цариця наук (Радовець Н.Я.)
Andy Levkovich
 

Viewers also liked (20)

Panorama
PanoramaPanorama
Panorama
 
Sistemas operativos 1 bach
Sistemas operativos 1 bachSistemas operativos 1 bach
Sistemas operativos 1 bach
 
Our Wonderful World! 1# LRC
Our Wonderful World! 1# LRCOur Wonderful World! 1# LRC
Our Wonderful World! 1# LRC
 
Christmas Pompon LRC
Christmas Pompon LRCChristmas Pompon LRC
Christmas Pompon LRC
 
2x360° Panorama (1)
2x360° Panorama (1)2x360° Panorama (1)
2x360° Panorama (1)
 
powerpoint
powerpointpowerpoint
powerpoint
 
Eksterno
EksternoEksterno
Eksterno
 
тема [автосохраненный] [восстановленный]
тема [автосохраненный] [восстановленный]тема [автосохраненный] [восстановленный]
тема [автосохраненный] [восстановленный]
 
критерії
критеріїкритерії
критерії
 
Натпревар по математика 2015/2016
Натпревар по математика 2015/2016Натпревар по математика 2015/2016
Натпревар по математика 2015/2016
 
читання
читаннячитання
читання
 
Boğazkere
BoğazkereBoğazkere
Boğazkere
 
Математика
МатематикаМатематика
Математика
 
математика
математикаматематика
математика
 
моите ученици
моите ученицимоите ученици
моите ученици
 
предлог задачи за подготовка за натпревар
предлог задачи за подготовка за натпреварпредлог задачи за подготовка за натпревар
предлог задачи за подготовка за натпревар
 
Bor moj grad copy
Bor moj grad   copyBor moj grad   copy
Bor moj grad copy
 
Шебер қолдар
Шебер қолдарШебер қолдар
Шебер қолдар
 
Математика цариця наук
Математика цариця наукМатематика цариця наук
Математика цариця наук
 
Математика цариця наук (Радовець Н.Я.)
Математика цариця наук (Радовець Н.Я.)Математика цариця наук (Радовець Н.Я.)
Математика цариця наук (Радовець Н.Я.)
 

Similar to Java programs

Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Java practical
Java practicalJava practical
Java practical
william otto
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
Srinivasa Babji Josyula
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
Srinivasa Babji Josyula
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
Kandarp Tiwari
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
Soumya Behera
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
mayorothenguyenhob69
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
CODEimport java.util.; public class test { public static voi.pdf
CODEimport java.util.; public class test { public static voi.pdfCODEimport java.util.; public class test { public static voi.pdf
CODEimport java.util.; public class test { public static voi.pdf
anurag1231
 
Lab4
Lab4Lab4
Computer programming 2 chapter 1-lesson 2
Computer programming 2  chapter 1-lesson 2Computer programming 2  chapter 1-lesson 2
Computer programming 2 chapter 1-lesson 2
MLG College of Learning, Inc
 
SumNumbers.java import java.util.Scanner;public class SumNumbe.pdf
SumNumbers.java import java.util.Scanner;public class SumNumbe.pdfSumNumbers.java import java.util.Scanner;public class SumNumbe.pdf
SumNumbers.java import java.util.Scanner;public class SumNumbe.pdf
ankkitextailes
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
Hari kiran G
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
Ajenkris Kungkung
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
university of education,Lahore
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Ayes Chinmay
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Java programs
Java programsJava programs
Java programs
Mukund Gandrakota
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
Aram Mohammed
 

Similar to Java programs (20)

Java Programs
Java ProgramsJava Programs
Java Programs
 
Java practical
Java practicalJava practical
Java practical
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
CODEimport java.util.; public class test { public static voi.pdf
CODEimport java.util.; public class test { public static voi.pdfCODEimport java.util.; public class test { public static voi.pdf
CODEimport java.util.; public class test { public static voi.pdf
 
Lab4
Lab4Lab4
Lab4
 
Computer programming 2 chapter 1-lesson 2
Computer programming 2  chapter 1-lesson 2Computer programming 2  chapter 1-lesson 2
Computer programming 2 chapter 1-lesson 2
 
SumNumbers.java import java.util.Scanner;public class SumNumbe.pdf
SumNumbers.java import java.util.Scanner;public class SumNumbe.pdfSumNumbers.java import java.util.Scanner;public class SumNumbe.pdf
SumNumbers.java import java.util.Scanner;public class SumNumbe.pdf
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Java programs
Java programsJava programs
Java programs
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
 

More from Dr.M.Karthika parthasarathy

IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...
IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...
IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...
Dr.M.Karthika parthasarathy
 
Linux Lab Manual.doc
Linux Lab Manual.docLinux Lab Manual.doc
Linux Lab Manual.doc
Dr.M.Karthika parthasarathy
 
Unit 2 IoT.pdf
Unit 2 IoT.pdfUnit 2 IoT.pdf
Unit 3 IOT.docx
Unit 3 IOT.docxUnit 3 IOT.docx
Unit 1 Introduction to Artificial Intelligence.pptx
Unit 1 Introduction to Artificial Intelligence.pptxUnit 1 Introduction to Artificial Intelligence.pptx
Unit 1 Introduction to Artificial Intelligence.pptx
Dr.M.Karthika parthasarathy
 
Unit I What is Artificial Intelligence.docx
Unit I What is Artificial Intelligence.docxUnit I What is Artificial Intelligence.docx
Unit I What is Artificial Intelligence.docx
Dr.M.Karthika parthasarathy
 
Introduction to IoT - Unit II.pptx
Introduction to IoT - Unit II.pptxIntroduction to IoT - Unit II.pptx
Introduction to IoT - Unit II.pptx
Dr.M.Karthika parthasarathy
 
IoT Unit 2.pdf
IoT Unit 2.pdfIoT Unit 2.pdf
Chapter 3 heuristic search techniques
Chapter 3 heuristic search techniquesChapter 3 heuristic search techniques
Chapter 3 heuristic search techniques
Dr.M.Karthika parthasarathy
 
Ai mcq chapter 2
Ai mcq chapter 2Ai mcq chapter 2
Ai mcq chapter 2
Dr.M.Karthika parthasarathy
 
Introduction to IoT unit II
Introduction to IoT  unit IIIntroduction to IoT  unit II
Introduction to IoT unit II
Dr.M.Karthika parthasarathy
 
Introduction to IoT - Unit I
Introduction to IoT - Unit IIntroduction to IoT - Unit I
Introduction to IoT - Unit I
Dr.M.Karthika parthasarathy
 
Internet of things Unit 1 one word
Internet of things Unit 1 one wordInternet of things Unit 1 one word
Internet of things Unit 1 one word
Dr.M.Karthika parthasarathy
 
Unit 1 q&amp;a
Unit  1 q&amp;aUnit  1 q&amp;a
Overview of Deadlock unit 3 part 1
Overview of Deadlock unit 3 part 1Overview of Deadlock unit 3 part 1
Overview of Deadlock unit 3 part 1
Dr.M.Karthika parthasarathy
 
Examples in OS synchronization for UG
Examples in OS synchronization for UG Examples in OS synchronization for UG
Examples in OS synchronization for UG
Dr.M.Karthika parthasarathy
 
Process Synchronization - Monitors
Process Synchronization - MonitorsProcess Synchronization - Monitors
Process Synchronization - Monitors
Dr.M.Karthika parthasarathy
 
.net progrmming part4
.net progrmming part4.net progrmming part4
.net progrmming part4
Dr.M.Karthika parthasarathy
 
.net progrmming part3
.net progrmming part3.net progrmming part3
.net progrmming part3
Dr.M.Karthika parthasarathy
 
.net progrmming part1
.net progrmming part1.net progrmming part1
.net progrmming part1
Dr.M.Karthika parthasarathy
 

More from Dr.M.Karthika parthasarathy (20)

IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...
IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...
IoT Enabled Wireless Technology Based Monitoring and Speed Control of Motor U...
 
Linux Lab Manual.doc
Linux Lab Manual.docLinux Lab Manual.doc
Linux Lab Manual.doc
 
Unit 2 IoT.pdf
Unit 2 IoT.pdfUnit 2 IoT.pdf
Unit 2 IoT.pdf
 
Unit 3 IOT.docx
Unit 3 IOT.docxUnit 3 IOT.docx
Unit 3 IOT.docx
 
Unit 1 Introduction to Artificial Intelligence.pptx
Unit 1 Introduction to Artificial Intelligence.pptxUnit 1 Introduction to Artificial Intelligence.pptx
Unit 1 Introduction to Artificial Intelligence.pptx
 
Unit I What is Artificial Intelligence.docx
Unit I What is Artificial Intelligence.docxUnit I What is Artificial Intelligence.docx
Unit I What is Artificial Intelligence.docx
 
Introduction to IoT - Unit II.pptx
Introduction to IoT - Unit II.pptxIntroduction to IoT - Unit II.pptx
Introduction to IoT - Unit II.pptx
 
IoT Unit 2.pdf
IoT Unit 2.pdfIoT Unit 2.pdf
IoT Unit 2.pdf
 
Chapter 3 heuristic search techniques
Chapter 3 heuristic search techniquesChapter 3 heuristic search techniques
Chapter 3 heuristic search techniques
 
Ai mcq chapter 2
Ai mcq chapter 2Ai mcq chapter 2
Ai mcq chapter 2
 
Introduction to IoT unit II
Introduction to IoT  unit IIIntroduction to IoT  unit II
Introduction to IoT unit II
 
Introduction to IoT - Unit I
Introduction to IoT - Unit IIntroduction to IoT - Unit I
Introduction to IoT - Unit I
 
Internet of things Unit 1 one word
Internet of things Unit 1 one wordInternet of things Unit 1 one word
Internet of things Unit 1 one word
 
Unit 1 q&amp;a
Unit  1 q&amp;aUnit  1 q&amp;a
Unit 1 q&amp;a
 
Overview of Deadlock unit 3 part 1
Overview of Deadlock unit 3 part 1Overview of Deadlock unit 3 part 1
Overview of Deadlock unit 3 part 1
 
Examples in OS synchronization for UG
Examples in OS synchronization for UG Examples in OS synchronization for UG
Examples in OS synchronization for UG
 
Process Synchronization - Monitors
Process Synchronization - MonitorsProcess Synchronization - Monitors
Process Synchronization - Monitors
 
.net progrmming part4
.net progrmming part4.net progrmming part4
.net progrmming part4
 
.net progrmming part3
.net progrmming part3.net progrmming part3
.net progrmming part3
 
.net progrmming part1
.net progrmming part1.net progrmming part1
.net progrmming part1
 

Recently uploaded

formative Evaluation By Dr.Kshirsagar R.V
formative Evaluation By Dr.Kshirsagar R.Vformative Evaluation By Dr.Kshirsagar R.V
formative Evaluation By Dr.Kshirsagar R.V
DrRavindrakshirsagar1
 
How to Store Data on the Odoo 17 Website
How to Store Data on the Odoo 17 WebsiteHow to Store Data on the Odoo 17 Website
How to Store Data on the Odoo 17 Website
Celine George
 
NLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacherNLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacher
AngelicaLubrica
 
How to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 NotebookHow to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 Notebook
Celine George
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Brajeswar Paul
 
Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?
Rakesh Jalan
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
HappieMontevirgenCas
 
How to Create Sequence Numbers in Odoo 17
How to Create Sequence Numbers in Odoo 17How to Create Sequence Numbers in Odoo 17
How to Create Sequence Numbers in Odoo 17
Celine George
 
OS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptx
OS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptxOS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptx
OS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptx
bipin95
 
How to Manage Early Receipt Printing in Odoo 17 POS
How to Manage Early Receipt Printing in Odoo 17 POSHow to Manage Early Receipt Printing in Odoo 17 POS
How to Manage Early Receipt Printing in Odoo 17 POS
Celine George
 
Unlocking Educational Synergy-DIKSHA & Google Classroom.pptx
Unlocking Educational Synergy-DIKSHA & Google Classroom.pptxUnlocking Educational Synergy-DIKSHA & Google Classroom.pptx
Unlocking Educational Synergy-DIKSHA & Google Classroom.pptx
bipin95
 
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Liyana Rozaini
 
Individual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docxIndividual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docx
monicaaringo1
 
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Murugan Solaiyappan
 
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at  Pangkabuhayan 1: Personal HygieneEdukasyong Pantahanan at  Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
MJDuyan
 
(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening
MJDuyan
 
Imagination in Computer Science Research
Imagination in Computer Science ResearchImagination in Computer Science Research
Imagination in Computer Science Research
Abhik Roychoudhury
 
Neuroimaging Mastery Project: Presentation #6 Subarachnoid Hemorrhage
Neuroimaging Mastery Project: Presentation #6 Subarachnoid HemorrhageNeuroimaging Mastery Project: Presentation #6 Subarachnoid Hemorrhage
Neuroimaging Mastery Project: Presentation #6 Subarachnoid Hemorrhage
Sean M. Fox
 
2024 KWL Back 2 School Summer Conference
2024 KWL Back 2 School Summer Conference2024 KWL Back 2 School Summer Conference
2024 KWL Back 2 School Summer Conference
KlettWorldLanguages
 
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ..."DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
thanhluan21
 

Recently uploaded (20)

formative Evaluation By Dr.Kshirsagar R.V
formative Evaluation By Dr.Kshirsagar R.Vformative Evaluation By Dr.Kshirsagar R.V
formative Evaluation By Dr.Kshirsagar R.V
 
How to Store Data on the Odoo 17 Website
How to Store Data on the Odoo 17 WebsiteHow to Store Data on the Odoo 17 Website
How to Store Data on the Odoo 17 Website
 
NLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacherNLC English 7 Consolidation Lesson plan for teacher
NLC English 7 Consolidation Lesson plan for teacher
 
How to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 NotebookHow to Add Colour Kanban Records in Odoo 17 Notebook
How to Add Colour Kanban Records in Odoo 17 Notebook
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
 
Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?Is Email Marketing Really Effective In 2024?
Is Email Marketing Really Effective In 2024?
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
 
How to Create Sequence Numbers in Odoo 17
How to Create Sequence Numbers in Odoo 17How to Create Sequence Numbers in Odoo 17
How to Create Sequence Numbers in Odoo 17
 
OS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptx
OS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptxOS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptx
OS ticketing tool: Troubleshooting Guide for DIKSHA’s concern.pptx
 
How to Manage Early Receipt Printing in Odoo 17 POS
How to Manage Early Receipt Printing in Odoo 17 POSHow to Manage Early Receipt Printing in Odoo 17 POS
How to Manage Early Receipt Printing in Odoo 17 POS
 
Unlocking Educational Synergy-DIKSHA & Google Classroom.pptx
Unlocking Educational Synergy-DIKSHA & Google Classroom.pptxUnlocking Educational Synergy-DIKSHA & Google Classroom.pptx
Unlocking Educational Synergy-DIKSHA & Google Classroom.pptx
 
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)
 
Individual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docxIndividual Performance Commitment Review Form-Developmental Plan.docx
Individual Performance Commitment Review Form-Developmental Plan.docx
 
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
 
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at  Pangkabuhayan 1: Personal HygieneEdukasyong Pantahanan at  Pangkabuhayan 1: Personal Hygiene
Edukasyong Pantahanan at Pangkabuhayan 1: Personal Hygiene
 
(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening
 
Imagination in Computer Science Research
Imagination in Computer Science ResearchImagination in Computer Science Research
Imagination in Computer Science Research
 
Neuroimaging Mastery Project: Presentation #6 Subarachnoid Hemorrhage
Neuroimaging Mastery Project: Presentation #6 Subarachnoid HemorrhageNeuroimaging Mastery Project: Presentation #6 Subarachnoid Hemorrhage
Neuroimaging Mastery Project: Presentation #6 Subarachnoid Hemorrhage
 
2024 KWL Back 2 School Summer Conference
2024 KWL Back 2 School Summer Conference2024 KWL Back 2 School Summer Conference
2024 KWL Back 2 School Summer Conference
 
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ..."DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
 

Java programs

  • 1. 1 | P a g e EX: 1 // HELLO WORLD class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); } } Output of program: EX:2 // If else in Java code import java.util.Scanner; class IfElse { public static void main(String[] args) { int marksObtained, passingMarks; passingMarks = 40; Scanner input = new Scanner(System.in); System.out.println("Input marks scored by you"); marksObtained = input.nextInt(); if (marksObtained >= passingMarks) { System.out.println("You passed the exam."); } else { System.out.println("Unfortunately you failed to pass the exam."); } } } Output of program: EX:3 // Nested If else in Java code import java.util.Scanner; class NestedIfElse { public static void main(String[] args) { int marksObtained, passingMarks; char grade; passingMarks = 40; Scanner input = new Scanner(System.in); System.out.println("Input marks scored by you");
  • 2. 2 | P a g e marksObtained = input.nextInt(); if (marksObtained >= passingMarks) { if (marksObtained > 90) grade = 'A'; else if (marksObtained > 75) grade = 'B'; else if (marksObtained > 60) grade = 'C'; else grade = 'D'; System.out.println("You passed the exam and your grade is " + grade); } else { grade = 'F'; System.out.println("You failed and your grade is " + grade); } } } Java for loop syntax for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) { // Statements to execute i.e. Body of for loop } Ex:4 // Infinite for loop for (;;) { System.out.println("Java programmer"); } Ex: 5 program below uses for loop to print first 10 natural numbers i.e. from 1 to 10. //Java for loop program class ForLoop { public static void main(String[] args) { int c; for (c = 1; c <= 10; c++) { System.out.println(c); } } } Output of program: Ex:6Java for loop example to print stars in console Following star pattern is printed * ** *** **** ***** class Stars { public static void main(String[] args) { int row, numberOfStars; for (row = 1; row <= 10; row++) {
  • 3. 3 | P a g e for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) { System.out.print("*"); } System.out.println(); // Go to next line } } } Output of program: JAVA WHILE LOOP while loop syntax: while (condition(s)) { // Body of loop } 1. If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false. 2. You can test multiple conditions such as while ( a > b && c != 0) { // Loop body } Loop body is executed till value of a is greater than value of b and c is not equal to zero. 3. Body of loop can contain more than one statement. For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}. It is recommended to use braces always to make your program easily readable and understandable. EX: 7 program asks the user to input an integer and prints it until user enter 0 (zero). import java.util.Scanner; class WhileLoop { public static void main(String[] args) { int n; Scanner input = new Scanner(System.in); System.out.println("Input an integer"); while ((n = input.nextInt()) != 0) { System.out.println("You entered " + n); System.out.println("Input an integer"); } System.out.println("Out of loop"); } }
  • 4. 4 | P a g e Output of program: Ex:8 // Printing alphabets class Alphabets { public static void main(String args[]) { char ch; for( ch = 'a' ; ch <= 'z' ; ch++ ) System.out.println(ch); } } You can easily modify the above java program to print alphabets in upper case.output of program: Printing alphabets using while loop (only body of main method is shown): char c = 'a'; while (c <= 'z') { System.out.println(c); c++; } Using do while loop: char c = 'A'; do { System.out.println(c); c++; } while (c <= 'Z'); Ex: 9 // program for multiplication table import java.util.Scanner; class MultiplicationTable { public static void main(String args[]) { int n, c; System.out.println("Enter an integer to print it's multiplication table"); Scanner in = new Scanner(System.in); n = in.nextInt(); System.out.println("Multiplication table of "+n+" is :-"); for ( c = 1 ; c <= 10 ; c++ ) System.out.println(n+"*"+c+" = "+(n*c)); } }
  • 5. 5 | P a g e Output of program: Retrieving input from the user Scanner a = new Scanner(System.in); Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below :- 1) nextInt to input an integer 2) nextFloat to input a float 3) nextLine to input a string Ex:10 import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { int a; float b; String s; Scanner in = new Scanner(System.in); System.out.println("Enter a string"); s = in.nextLine(); System.out.println("You entered string "+s); System.out.println("Enter an integer"); a = in.nextInt(); System.out.println("You entered integer "+a); System.out.println("Enter a float"); b = in.nextFloat(); System.out.println("You entered float "+b); } } Output of program: Ex:11 import java.util.Scanner; class AddNumbers { public static void main(String args[]) { int x, y, z; System.out.println("Enter two integers to calculate their sum "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); z = x + y; System.out.println("Sum of entered integers = "+z); } }
  • 6. 6 | P a g e Output of program: Ex:12 import java.util.Scanner; class OddOrEven { public static void main(String args[]) { int x; System.out.println("Enter an integer to check if it is odd or even "); Scanner in = new Scanner(System.in); x = in.nextInt(); if ( x % 2 == 0 ) System.out.println("You entered an even number."); else System.out.println("You entered an odd number."); } } Output of program: Ex:13 Another method to check odd or even import java.util.Scanner; class EvenOdd { public static void main(String args[]) { int c; System.out.println("Input an integer"); Scanner in = new Scanner(System.in); c = in.nextInt(); if ( (c/2)*2 == c ) System.out.println("Even"); else System.out.println("Odd"); } } EX:15 //Fahrenheit to Celsius import java.util.*; class FahrenheitToCelsius { public static void main(String[] args) { float temperatue; Scanner in = new Scanner(System.in); System.out.println("Enter temperatue in Fahrenheit"); temperatue = in.nextInt(); temperatue = ((temperatue - 32)*5)/9; System.out.println("Temperatue in Celsius = " + temperatue); } }
  • 7. 7 | P a g e Output of program: [ For Celsius to Fahrenheit conversion use T = 9*T/5 + 32 where T is temperature on Celsius scale.] ** Create and test Fahrenheit to Celsius program yourself for practice. Java methods Java program consists of one or more classes and a class may contain method(s). A class can do very little without methods. A method has a name and return type. Main method is a must in a Java program as execution begins from it. Syntax of methods "Access specifier" "Keyword(s)" "return type" methodName(List of arguments) { // Body of method } Access specifier can be public or private which decides whether other classes can call a method. Keywords are used for some special methods such as static or synchronized. Return type indicate return value which method returns. Method name is a valid Java identifier name.  Access specifier, Keyword and arguments are optional. Examples of methods declaration: public static void main(String[] args); void myMethod(); private int maximum(); public synchronized int search(java.lang.Object); Ex:16 class Methods { // Constructor method Methods() { System.out.println("Constructor method is called when an object of it's class is created"); } // Main method where program execution begins public static void main(String[] args) { staticMethod(); Methods object = new Methods(); object.nonStaticMethod(); } // Static method static void staticMethod() { System.out.println("Static method can be called without creating object");
  • 8. 8 | P a g e } // Non static method void nonStaticMethod() { System.out.println("Non static method must be called by creating an object"); } } Output of program: Java methods list Java has a built in library of many useful classes and there are thousands of methods which can be used in your programs. javap package.classname For example javap java.lang.String // list all methods and constants of String class. javap java.math.BigInteger // list constants and methods of BigInteger class in java.math package Java String methods String class contains methods which are useful for performing operations on String(s). Below program illustrate how to use inbuilt methods of String class. Java string class program EX:15 class StringMethods { public static void main(String args[]) { int n; String s = "Java programming", t = "", u = ""; System.out.println(s); // Find length of string n = s.length(); System.out.println("Number of characters = " + n); // Replace characters in string t = s.replace("Java", "C++"); System.out.println(s); System.out.println(t); // Concatenating string with another string u = s.concat(" is fun"); System.out.println(s); System.out.println(u); } } Output of program: Ex:16 Array input at run time import java.io.*; import java.util.Scanner; class arrayruntime { public static void main(String args[]) { Scanner a =new Scanner(System.in); int a1[] = new int[5]; int j= a1.length;
  • 9. 9 | P a g e for(int i=0;i<j;i++) { int k= a.nextInt(); a1[i]=k; } for(int i=0;i<j;i++) { System.out.println(a1[i]); } } } Output Java arrayruntime 45 45 57 35 29 45 45 57 35 29 Ex:17 Sorting odd and even import java.io.*; import java.util.Scanner; class arrayruntimeoddeven { public static void main(String args[]) { Scanner a =new Scanner(System.in); int a1[] = new int[5]; int j= a1.length; for(int i=0;i<j;i++) { int k= a.nextInt(); a1[i]=k; } System.out.println("The array is"); for(int i=0;i<j;i++) { System.out.println(a1[i]); } for(int i=0;i<j;i++) { if(a1[i]%2==0) { int l = a1[i]; System.out.println(l+" is even"); } else { int l = a1[i]; System.out.println(l+" is odd"); } } } } Output C:Program FilesJavajdk1.6.0_13bin>java arrayruntimeoddeven 23 33 54 32 78 The array is 23 33 54 32 78 23 is odd 33 is odd 54 is even 32 is even 78 is even
  • 10. 10 | P a g e Ex:18 Constructor class area { int length; int breadth; area ( int a, int b)//constructor { length =a; breadth =b; } int rectarea() { int area2 =length*breadth; return area2; } } class constructor { public static void main(String args[]) { int area1; area a1 = new area(12,15); //a1.getdata(12,15); area1 = a1.rectarea(); System.out.println("area is "+area1); } } Output C:Program FilesJavajdk1.6.0_13bin>java constructor area is 180 Ex:19 getinput during execution class get { public static void main(String args[]) { int a= Integer.parseInt(args[0]); System.out.println(a); } } Output C:Program FilesJavajdk1.6.0_13bin>java get 2 2 Ex:20 Get user input at runtime using bufferedreader import java.io.*; public class getuserinput { public static void main (String[] args) { System.out.print("Enter your name and press Enter: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String name = null; try { name = br.readLine(); } catch (IOException e) { System.out.println("Error!"); System.exit(1); } System.out.println("Your name is " + name); } } Output C:Program FilesJavajdk1.6.0_13bin>javac getuserinput.java C:Program FilesJavajdk1.6.0_13bin>java getuserinput Enter your name and press Enter: sudharsun Your name is sudharsun
  • 11. 11 | P a g e Ex:21 Inheritance class Room { int length; int breadth; Room (int x,int y) { length =x; breadth=y; } } class BedRoom extends Room { int height; BedRoom(int x,int y, int z) { super(x,y); height =z; } int volume() { return(length*breadth*height); } } class inheritance { public static void main(String args[]) { BedRoom r1= new BedRoom(2,4,5); int vol = r1.volume(); System.out.println(vol); } } Output C:Program FilesJavajdk1.6.0_13bin>javac inheritance.java C:Program FilesJavajdk1.6.0_13bin>java inheritance 40 Ex:22 Get input using data input stream import java .io.DataInputStream; class input { public static void main(String args[]) { DataInputStream in = new DataInputStream(System.in); int i=0; try { i=Integer.parseInt(in.readLine()); } catch (Exception e) { } System.out.println(i); } } Output C:Program FilesJavajdk1.6.0_13bin>java input 23 23 Ex:23 Overloading class area { int length; int breadth; area(int x,int y) /*using constructor*/ { length= x; breadth= y; } area(int x) /*using constructor*/ { length=breadth=x; } int area1() { return(length*breadth); }
  • 12. 12 | P a g e } class overload { public static void main(String args[]) { area r1 = new area(2,3);/*calling Constructor*/ area r2 = new area(3); int a1 = r1.area1(); int a2 = r2.area1(); System.out.println(a1); System.out.println(a2); } } Output C:Program FilesJavajdk1.6.0_13bin>javac overload.java C:Program FilesJavajdk1.6.0_13bin>java overload 6 9 Ex:24 Overload program 2 input at runtime class room { int length; int breadth; room(int x,int y) { length= x; breadth= y; } room(int x) { length=breadth=x; } int area() { return(length*breadth); } } class overload1 { public static void main(String args[]) { int i= Integer.parseInt(args[0]); int j= Integer.parseInt(args[1]); room r1 = new room(i,j); int k= Integer.parseInt(args[2]); room r2 = new room(k); int area1 = r1.area(); int area2 = r2.area(); System.out.println(area1); System.out.println(area2); } } Output C:Program FilesJavajdk1.6.0_13bin>java overload1 101 101 12 10201 144 Ex:25 Overriding class superclass { int x; superclass(int x) { this.x=x; } void display() { System.out.println(x); } } class subclass extends superclass { int y; subclass(int x , int y) { super(x); this.y=y; } void display() {
  • 13. 13 | P a g e System.out.println(y); } } class overriding { public static void main(String args[]) { subclass s1=new subclass(100,200); s1.display(); } } Output C:Program FilesJavajdk1.6.0_13bin>javac overriding.java C:Program FilesJavajdk1.6.0_13bin>java overriding 200 Ex:26 Replace a letter in a word class replace { public static void main(String args[]) { String s1= "Hello"; System.out.println(s1); String s2 = s1.replaceFirst("lo","p"); System.out.println(s2); } } Output C:Program FilesJavajdk1.6.0_13bin>java replace Hello Help Ex:27 Sample program for java class area { int length;// int breadth;//Field Decl void getdata( int a, int b)//Method Decl { length =a; breadth =b; } int rectarea() { int area =length*breadth; return area; } } class sample { public static void main(String args[]) { int area1; area a1 = new area(); a1.getdata(12,15); area1 = a1.rectarea(); System.out.println("area is "+area1); } } Output C:Program FilesJavajdk1.6.0_13bin>javac sample.java C:Program FilesJavajdk1.6.0_13bin>java sample area is 180 Ex:28 get user input using scanner import java.io.*; import java.util.Scanner; public class scanner { public static void main (String[] args) { Scanner in = new Scanner(System.in); String i; i=in.nextLine(); // String i= next();// Does not read spaces //int i= nextInt();// read integer and for float and double add them int the palce of next"Int"
  • 14. 14 | P a g e System.out.println(i); } } Output C:Program FilesJavajdk1.6.0_13bin>javac scanner.java C:Program FilesJavajdk1.6.0_13bin>java scanner 10 10 Ex:29 Display of substring class str1 { public static void main(String args[]) { String s1 ="hello"; String s2 ="hello"; System.out.println(s1.substring(0,2)+"lp"); char s3 = s1.charAt(3); System.out.println(s3); if (s1.equals(s2)) { System.out.println("true"); } else { System.out.println("false"); } String s4 =s1.substring(0,2); System.out.println(s4); } } Output C:Program FilesJavajdk1.6.0_13bin>java str1 help l true he Ex:30 call of an function class functioncall { public static void funct1 () { System.out.println ("Inside funct1"); } public static int funct2 (int param) { System.out.println ("Inside funct2 with param " + param); return param * 2; } public static void main (String[] args) { int val; System.out.println ("Inside main"); funct1(); System.out.println ("About to call funct2"); val = funct2(8); System.out.println ("funct2 returned a value of " + val); } } Output C:Program FilesJavajdk1.6.0_13bin>javac functioncall.java C:Program FilesJavajdk1.6.0_13bin>java functioncall Inside main Inside funct1 About to call funct2 Inside funct2 with param 8 funct2 returned a value of 16 Ex:31 display the current date
  • 15. 15 | P a g e import java.util.*; class hellodate { public static void main (String[] args) { System.out.println ("Hello, it's: "); System.out.println(new Date()); } } Output C:Program FilesJavajdk1.6.0_13bin>javac hellodate.java C:Program FilesJavajdk1.6.0_13bin>java hellodate Hello, it's: Thu Sep 29 11:05:16 GMT+05:30 2011 Ex:32 Lab program (rational number) import java.io.*; import java.util.Scanner; public class rational { public static void main(String args[]) { System.out.println("The give required Numbers "); Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); int i; System.out.println("The given rational Number is"); System.out.println(a+"/"+b); if(a<b) { for(i=2;i<=9;i++) { while(a%i==0 && b%i==0) { a=a/i; b=b/i; } } } else { for(i=2;i<=9;i++) { while(a%i==0 && b%i==0) { a=a/i; b=b/i; } } } System.out.println("The simplified rational number is"); System.out.println(a+"/"+b); } } Output C:Program FilesJavajdk1.6.0_13bin>javac rational.java C:Program FilesJavajdk1.6.0_13bin>java rational The give required Numbers 3 54 The given rational Number is 3/54 The simplified rational number is 1/18 Ex:33 Reverse an number eg 10 01 public class ReverseNumber { public static void main(String[] args) { int number = 1234; int reversedNumber = 0; int temp = 0; while(number > 0) { temp = number%10; reversedNumber = reversedNumber * 10 + temp;
  • 16. 16 | P a g e number = number/10; } System.out.println("Reversed Number is: " + reversedNumber); } } Output C:Program FilesJavajdk1.6.0_13bin>javac ReverseNumber.java C:Program FilesJavajdk1.6.0_13bin>java ReverseNumber Reversed Number is: 4321 Ex:34 Swap function call eg a=5 b=6 a=6 b=5 public class swap { public static void main(String[] args) { int num1 = 10; int num2 = 20; System.out.println("Before Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; System.out.println("Before Swapping"); System.out.println("Value of num1 is :" + num1); System.out.println("Value of num2 is :" +num2); } } Output C:Program FilesJavajdk1.6.0_13bin>javac swap.java C:Program FilesJavajdk1.6.0_13bin>java swap Before Swapping Value of num1 is :10 Value of num2 is :20 Before Swapping Value of num1 is :20 Value of num2 is :10 Ex:35 Program to compare string import java.util.Scanner; class Compare_Strings { public static void main(String args[]) { String s1, s2; Scanner in = new Scanner(System.in); System.out.println("Enter the first string"); s1 = in.nextLine(); System.out.println("Enter the second string"); s2 = in.nextLine(); if ( s1.compareTo(s2) > 0 ) System.out.println("First string is greater than second."); else if ( s1.compareTo(s2) < 0 ) System.out.println("First string is smaller than second."); else System.out.println("Both strings are equal."); } } Output C:Program FilesJavajdk1.6.0_13bin>javac Compare_Strings.java
  • 17. 17 | P a g e C:Program FilesJavajdk1.6.0_13bin>java Compare_Strings Enter the first string sun Enter the second string sun Both strings are equal. Ex:36 Sorting string in an array import java.util.Arrays; public class ArrayStringSorting { public static void main(String[] args) { String[] arrayList = new String[] { "Thirumal", "Banana", "Apple", "Pears", "Orange" }; System.out.println("Before sorting the array: " + Arrays.asList(arrayList)); Arrays.sort(arrayList); // sort method used to sort the array contents . System.out.println("After sorting the array: " + Arrays.asList(arrayList)); } } Output C:Program FilesJavajdk1.6.0_13bin>java ArrayStringSorting Before sorting the array: [Thirumal, Banana, Apple, Pears, Orange] After sorting the array: [Apple, Banana, Orange, Pears, Thirumal] Ex:37 Program to change the colour of the background import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * @version 1.33 2007-06-12 * @author Cay Horstmann */ public class ActionTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { ActionFrame frame = new ActionFrame(); frame.setDefaultCloseOperation(JFrame.E XIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * A frame with a panel that demonstrates color change actions. */ class ActionFrame extends JFrame { public ActionFrame() { setTitle("ActionTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); buttonPanel = new JPanel(); // define actions Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow- ball.gif"),Color.YELLOW); Action blueAction = new ColorAction("Blue", new ImageIcon("blue- ball.gif"), Color.BLUE); Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); // add buttons for these actions
  • 18. 18 | P a g e buttonPanel.add(new JButton(yellowAction)); buttonPanel.add(new JButton(blueAction)); buttonPanel.add(new JButton(redAction)); // add panel to frame add(buttonPanel); // associate the Y, B, and R keys with names InputMap imap = buttonPanel.getInputMap(JComponent.W HEN_ANCESTOR_OF_FOCUSED_COMPONE NT); imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow"); imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue"); imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red"); // associate the names with actions ActionMap amap = buttonPanel.getActionMap(); amap.put("panel.yellow", yellowAction); amap.put("panel.blue", blueAction); amap.put("panel.red", redAction); } public class ColorAction extends AbstractAction { /** * Constructs a color action. * @param name the name to show on the button * @param icon the icon to display on the button * @param c the background color */ public ColorAction(String name, Icon icon, Color c) { putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toUpperCase()); putValue("color", c); } public void actionPerformed(ActionEvent event) { Color c = (Color) getValue("color"); buttonPanel.setBackground(c); } } private JPanel buttonPanel; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } Ex:38 Testing the button import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class ButtonTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { ButtonFrame frame = new ButtonFrame(); frame.setDefaultCloseOperation(JFrame.E XIT_ON_CLOSE); frame.setVisible(true);
  • 19. 19 | P a g e } }); } } @SuppressWarnings("serial") class ButtonFrame extends JFrame { private final static int DEFAULT_WIDTH = 300; private final static int DEFAULT_HEIGHT = 200; private final JPanel buttonPanel; public ButtonFrame() { this.setTitle("Button Frame"); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.buttonPanel = new JPanel(); PanelButton yellowButton = new PanelButton("Yellow", Color.YELLOW, buttonPanel); PanelButton redButton = new PanelButton("Red", Color.RED, buttonPanel); PanelButton blueButton = new PanelButton("Blue", Color.BLUE, buttonPanel); this.buttonPanel.add(yellowButton); this.buttonPanel.add(redButton); this.buttonPanel.add(blueButton); // add panel to frame this.add(this.buttonPanel); } } @SuppressWarnings("serial") class PanelButton extends JButton implements ActionListener { private final Color buttonColor; private final JPanel buttonPanel; public PanelButton(String title, Color buttonColor, JPanel buttonPanel) { super(title); this.buttonColor = buttonColor; this.buttonPanel = buttonPanel; this.addActionListener(this); } @Override public void actionPerformed(ActionEvent event) { buttonPanel.setBackground(this.buttonCol or); } } Ex:39 Mouse event import java.awt.*; import java.awt.event.*; import java.util.*; import java.awt.geom.*; import javax.swing.*; /** * @version 1.32 2007-06-12 * @author Cay Horstmann */ public class MouseTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { MouseFrame frame = new MouseFrame(); frame.setDefaultCloseOperation(JFrame.E XIT_ON_CLOSE); frame.setVisible(true); } }); }
  • 20. 20 | P a g e } /** * A frame containing a panel for testing mouse operations */ class MouseFrame extends JFrame { public MouseFrame() { setTitle("MouseTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add component to frame MouseComponent component = new MouseComponent(); add(component); } public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } /** * A component with mouse operations for adding and removing squares. */ class MouseComponent extends JComponent { public MouseComponent() { squares = new ArrayList<Rectangle2D>(); current = null; addMouseListener(new MouseHandler()); addMouseMotionListener(new MouseMotionHandler()); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // draw all squares for (Rectangle2D r : squares) g2.draw(r); } /** * Finds the first square containing a point. * @param p a point * @return the first square that contains p */ public Rectangle2D find(Point2D p) { for (Rectangle2D r : squares) { if (r.contains(p)) return r; } return null; } /** * Adds a square to the collection. * @param p the center of the square */ public void add(Point2D p) { double x = p.getX(); double y = p.getY(); current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH,SIDELENGTH); squares.add(current); repaint(); } /** * Removes a square from the collection. * @param s the square to remove */ public void remove(Rectangle2D s) {
  • 21. 21 | P a g e if (s == null) return; if (s == current) current = null; squares.remove(s); repaint(); } private static final int SIDELENGTH = 10; private ArrayList<Rectangle2D> squares; private Rectangle2D current; // the square containing the mouse cursor private class MouseHandler extends MouseAdapter { public void mousePressed(MouseEvent event) { // add a new square if the cursor isn't inside a square current = find(event.getPoint()); if (current == null) add(event.getPoint()); } public void mouseClicked(MouseEvent event) { // remove the current square if double clicked current = find(event.getPoint()); if (current != null && event.getClickCount() >= 2) remove(current); } } private class MouseMotionHandler implements MouseMotionListener { public void mouseMoved(MouseEvent event) { // set the mouse cursor to cross hairs if it is inside // a rectangle if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor()); else setCursor(Cursor.getPredefinedCursor(Cur sor.HAND_CURSOR )); } public void mouseDragged(MouseEvent event) { if (current != null) { int x = event.getX(); int y = event.getY(); // drag the current rectangle to center it at (x, y) current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH); repaint(); } } } } Implementation of look and feel import java.awt.EventQueue; import java.awt.event.*; import javax.swing.*; /** * @version 1.32 2007-06-12 * @author Cay Horstmann */ public class PlafTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() {
  • 22. 22 | P a g e public void run() { PlafFrame frame = new PlafFrame(); frame.setDefaultCloseOperation(JFrame.E XIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * A frame with a button panel for changing look and feel */ class PlafFrame extends JFrame { public PlafFrame() { setTitle("PlafTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); buttonPanel = new JPanel(); UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo info : infos) makeButton(info.getName(), info.getClassName()); add(buttonPanel); } /** * Makes a button to change the pluggable look and feel. * @param name the button name * @param plafName the name of the look and feel class */ void makeButton(String name, final String plafName) { // add button to panel JButton button = new JButton(name); buttonPanel.add(button); // set button action button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // button action: switch to the new look and feel try { UIManager.setLookAndFeel(plafName); SwingUtilities.updateComponentTreeUI(Pl afFrame.this); } catch (Exception e) { e.printStackTrace(); } } }); } private JPanel buttonPanel; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; }