Kts Java 2 Marks
Kts Java 2 Marks
UNIT- I
Introduction to Java - Features of Java - Object Oriented Concepts - Data Types - Variables -
Arrays - Operators - Control Statements-Input and output-Scanner and System class-
print(),println(), and printf() methods.
UNIT- II
Classes - Objects - Constructors - Overloading method - Access Control - Static and fixed
methods - Inner Classes - String Class - Inheritance - Overriding methods - Using super-
Abstract class – Type Wrapper classes for primitive types – Auto boxing and auto Unboxing --
Recursion.
UNIT- III
GUI components – Common GUI Event types and Listener Interfaces- JoptionPane –
JLabel, JTextfield, JButton,JCheckBox,JTextarea, JComboBox, JList, JPannel. – Mouse
Event Handling - Adapter Classes- Key Event Handling.
UNIT- IV
Mouse Event Handling - Adapter Classes- Key Event Handling. Layout Managers –
FlowLayout, BorderLayout, GridLayout.- Graphics contexts and graphics objects – color
control – font control – Drawing lines,rectangles and ovals –jslider-using menus with frames.
UNIT- V
Packages - Access Protection - Importing Packages - Interfaces - Exception Handling -
Throw and Throws - Thread - Synchronization - Runnable Interface - Inter thread
Communication – Multithreading.- file streams-Sequential file , Random file.
Text Books
Programming in Java – 2nd Edition by C.Muthu, TMH Publication
Java How to Program by Deitel & Deitel - 6th Edition- PHI Publication 2005.
Byte code
Java programs are translated into an intermediate language called bytecode.
Byte code is the same no matter which computer platform it is run on.
Byte code is translated into native code that the computer can execute on a program
called the Java Virtual Machine (JVM).
The Byte code can be executed on any computer that has the JVM. Hence Java’s slogan,
“Write once, run anywhere”.
The Java Environment
Data Types
A data type is a scheme for representing values. An example is int which is the integer, a
data type.
Values are not just numbers, but any kind of data that a computer can process.
The data type defines the kind of data that is represented by a variable.
As with the keyword class, Java data types are case sensitive.
Primitive Java Data Types
Objects
• All data in Java falls into one of two categories: primitive data and objects. There are only
eight primitive data types. Any data type you create will be an object.
• An object is a structured block of data. An object may use many bytes of memory.
• The data type of an object is its class.
• Many classes are already defined in the Java Development Kit.
• A programmer can create new classes to meet the particular needs of a program.
Variables
• Variables are labels that describe a particular location in memory and associate it with a data
type.
Array Definition:
A dimensional array is a structure created in the memory to represent a number of teh same type
of data (i.e integer/string/characters)withg the help of a single variable.
Creating ,Initializing,and Declaring Array Variables:
One way to create an array is with the new operator. To use an array in a program, you must
declare a variable to reference the array, and you must specify the type of array the variable can
reference. Here is the syntax for declaring an array variable: e.g int a[]=new int[10];
Advantage of Java Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Disadvantage of Java Array
Size Limit: We can store only fixed size of elements in the array. It doesn’t grow its size at
runtime. To solve this problem, collection framework is used in java.
Types of an Array
A dimensional array is two types. 1. Single dimensional Array 2. Multiple Dimensional Array
/* Java Factorial Example */ /*Swap Numbers Without Using Third Variable */
import java.io.*; import java.io.*;
class fact class swap
{ public static void main(String[] args) { public static void main(String[] args)
{ int number = 5; { int num1 = 10;
int factorial = number; int num2 = 20;
for(int i =(number – 1); i > 1; i–) System.out.println(“Before Swapping”);
factorial = factorial * i; System.out.println(“num1 is :” + num1);
System.out.println(“Factorial is ” + factorial); System.out.println(“num2 is :” +num2);
}
num1 = num1 + num2;
}
num2 = num1 – num2;
/* Reverse Number using Java*/
num1 = num1 – num2;
import java.io.*;
System.out.println(“After Swapping”);
public class reverse
System.out.println(“num1 Value is :” + num1);
{ public static void main(String[] args)
System.out.println(“num2 Value is :” +num2);
{ //original number
}
int number = 3456;
}
int reversedNum = 0;
int temp = 0;
while(number > 0)
{ temp = number%10;
reversedNum = reversedNum* 10 + temp;
number = number/10; }
System.out.println(“Reversed Number is: ”
+ reversedNum);
}
}
/* Fibonacci Number using Java*/
import java.io.*;
class FibonacciExample
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+” “+n2); //printing 0 and 1
for(i=2;i<count;++i) {
n3=n1+n2;
System.out.print(” “+n3);
n1=n2;
n2=n3;
}
}
}
g.setColor( Color.red );
g.drawOval( 50, 225, 100, 50 );
g.setColor( Color.orange );
g.fillOval( 225, 37, 50, 25 );
g.setColor( Color.magenta );
g.drawArc( 10, 110, 80, 80, 90, 180 );
g.setColor( Color.cyan );
g.fillArc( 140, 40, 120, 120, 90, 45 );
g.setColor( Color.yellow );
g.fillArc( 150, 150, 100, 100, 90, 90 );
g.setColor( Color.black );
g.fillArc( 160, 160, 80, 80, 90, 90 );
g.setColor( Color.green );
g.drawString( “computernotes.in by Veneeta phutela!”, 50, 150 );
}
}
/*<applet code=”DrawStuff.class” height=300 width=400>
</applet>*/
A number is called prime number if its not divisible by any number other than 1 or itself
and you can use this logic to check whether a number is prime or not.It is called
a composite number.
import java.util.*;
class Prime
{
public static void main(String args[])
{
int n, i, res;
boolean flag=true;
Scanner scan= new Scanner(System.in);
System.out.println(“Please Enter a No.”);
n=scan.nextInt();
for(i=2;i<=n/2;i++)
{
res=n%i;
if(res==0)
{
flag=false;
break;
}
}
if(flag)
System.out.println(n + ” is Prime Number”);
else
System.out.println(n + ” is not Prime Number”);
}
}
{
int n, reverse = 0;
System.out.println(“Enter the number to reverse”);
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println(“Reverse of entered number is “+reverse);
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153
where:
(3*3*3)=27
(7*7*7)=343
(1*1*1)=1
So:
27+343+1=371
import java.util.*;
import java.io.*;
class arm
{
int n = ob.nextInt();
int r,sum=0,temp = n;
while(n>0)
r=n%10;
n=n/10;
sum=sum+(r*r*r);
if(sum==temp)
else
For Example :- 37 is prime number , and its reverse order is 73 and 73 is also prime
number.
import java.io.*;
System.out.println(“Input a number”);
n=Integer.parseInt(in.readLine());
m=n;
int p=m;
while(m!=0)
r=m%10;
s=(s*10)+r;
m=m/10; }
for(i=2;i<n;i++)
if(n%i==0)
k++;
}}
for(j=2;j<s;j++)
if(s%j==0)
c++;
}}
if(k==0&c==0)
else
System.out.println(“Before Swapping”);
System.out.println(“Value of num1 is :” + num1);
System.out.println(“Value of num2 is :” +num2);
//swap the value
swap(num1, num2);
}
private static void swap(int num1, int num2) {
System.out.println(“After Swapping”);
System.out.println(“Value of num1 is :” + num1);
System.out.println(“Value of num2 is :” +num2);
}
}
Exapmle of Palindrome Strings are Liril, Radar, Level, Mom, Dad, Malayalam, Civic,
Madam, Bob, Pop, Refer, Rotator, Stats.
Example Java Program to check whether a given number or string is palindrome or not
import java.util.*;
public class PalindromeSt
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println(“Please enter a number: “);
int num = scanner.nextInt();
System.out.println(“Please enter a string: “);
String str = scanner.next();
Palindromest palin = new Palindromest();
int revNum = palin.reverse(num);
String revStr = palin.reverse(str);
if (num == revNum)
{
System.out.printf(“\n The number %d is a Palindrome “, num);
}
else
{
System.out.printf(“\n The number %d is not a Palindrome “, num);
}
if (str.equalsIgnoreCase(revStr))
{
System.out.printf(“\n The string ‘%s’ is a Palindrome “, str);
}
else
{
System.out.printf(“\n The string ‘%s’ is not a Palindrome “, str);
}
}
// Method to return the reverse of a number
public int reverse(int num)
{
int revNum = 0;
while (num > 0)
{
int rem = num % 10;
revNum = (revNum * 10) + rem;
num = num / 10;}
return revNum;}
// Method to return the reverse of a string
public String reverse(String str)
{
StringBuilder revStr = new StringBuilder();
for (int i = str.length()-1; i >= 0; i–)
{
revStr.append(str.charAt(i));
}
return revStr.toString();
}
}
Perfect Number:- If the sum of all the factors of a number is equal to the
number itself then it is a perfect number. For example, 6 is a perfect number since
the sum of its divisors (1 + 2 + 3) is equal to 6. This program finds whether a
given number is perfect number or not..
import java.io.*;
import java.util.*;
class perfectnumber
System.out.print(“\nEnter a number:”);
int n = Integer.parseInt(br.readLine());
int sum = 0;
for(int i=1;i<n;i++)
if(n%i==0)
sum = sum + i;
if(sum == n)
else
Binding:
Connecting a method call to the method body is known as binding.There are two types of
binding.
//……….
System.out.println(“cat walks”);
}
obj1.walk();
Here we have created an object of cat class and calling the method walk() of the same
class. Since nothing is ambiguous here, compiler would be able to resolve this binding
during compile-time, such kind of binding is known as static binding.
Static binding with overloaded function in Java :
class abc
System.out.println(“int value=”+a);
System.out.println(“float value=”+b);
System.out.println(“String value=”+c);
}
}
class xyz
a1.sum(10);
a1.sum(2.4);
a1.sum(“Ram”);
output:
sum=10
sum=2.7
sum=Ram
Dynamic binding:
Dyanmic Binding is a RunTime operation.Overridden methods are bounded using dynamic
binding at runtime.
System.out.println(“animal walks”);
l{
System.out.println(“cat walks”);
{
//Reference is of parent class
animal obj = new cat();
obj.walk();
Output:
cat walks
}}
class abc
System.out.println(“int value=”+a);
System.out.println(“float value=”+b);
}
public void sum(String c)
System.out.println(“String value=”+c);
class xyz
a1.sum(10);
a1.sum(2.4);
a1.sum(“Ram”);
output:
sum=10
sum=2.7
sum=Ram
class abc
System.out.println(“sum=”+a);
System.out.println(“sum=”+b+”,”+c);
System.out.println(“sum=”+d+”,”+e+”,”+f);
class xyz
a1.sum(10);
a1.sum(10,20);
a1.sum(10,20,30);
output:
sum=10
sum=10,20
sum=10,20,30
class animal{
System.out.println(“I am a animal.”);
System.out.println(“I am a dog.”);
}
class goat extends animal
System.out.println(“I am a goat.”);
System.out.println(“I am a cat.”);
class RunPoly
ref1.whoru();
ref2.whoru();
ref3.whoru();
ref4.whoru();
output :
I am a animal.
I am a dog.
I am a goat.
I am a cat.
In the example, there are four variables of type animal (e.g., ref1, ref2, ref3, and ref4).
Only ref1 refers to an instance of animal class, all others refer to an instance of the
subclasses of animal. From the output results, you can confirm that version of a method is
invoked based on the actually object’s type.
The program is able to resolve the correct method related to the subclass object at runtime.
This is called the runtime polymorphism in Java. This provides the ability to override
functionality already available in the class hierarchy tree. At runtime, which version of the
method will be invoked is based on the type of actual object stored in that reference
variable and not on the type of the reference variable.
class Student
int yearCourse;
super(name, stutId);
this.yearCourse = yearCourse;
}
public void printStudent()
super.printStudent();
class school
s1.printStudent();
}
In above example:
The printStudent() underlined above is equivalent to:
}
The path is required to be set for using tools such as javac, java etc. If you are saving the
java source file inside the jdk/bin directory, path is not required to be set because all the
tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set path of
JDK.
String Handling provides a lot of concepts that can be performed on a string such as
concatenating string, comparing string, substring etc.
Let’s first understand what is string and how we can create the string object.
Strings
which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
String
Generally string is a sequence of characters. But in java, string is an object. String class is
used to create string object.
Creating Strings:
1. By string literal
2. By new keyword
1) String literal
String literal is created by double quote.For Example:
1. String s=”Hello”;
Each time when we create a string literal, the JVM checks the string constant pool first. If
the string already exists in the pool, a reference to the pooled instance returns. If the string
does not exist in the pool, a new String object instantiates, then is placed in the pool.For
example:
1. String s1=”Java”;
2. String s2=”Java”;//no new object will be created
In the above example only one object will be created.First time JVM will find no string
object with the name “Welcome” in string constant pool,so it will create a new
object.Second time it will find the string with the name “Welcome” in string constant
pool,so it will not create new object whether will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool
inside the Heap memory.
The most direct way to create a string is to write:
String str = “Hello world!”;
Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, “Hello world!’.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has eleven constructors that allow you to provide the initial
value of the string using different sources, such as an array of characters.e.g.
output :
hello.
Note: The String class is immutable, so that once it is created a String object cannot be
changed. If there is a necessity to make a lot of modifications to Strings of characters, then
you should use String Buffer & String Builder Classes.
2) By new keyword
String s=new String(“Java”);//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and the
literal “Welcome” will be placed in the string constant pool.The variable s will refer to the
object in Heap(nonpool).
public class StringDemo{
public static void main(String args[])
{
char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String helloString = new String(helloArray);
System.out.println( helloString );
}}