0% found this document useful (0 votes)
21 views

Kts Java 2 Marks

Uploaded by

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

Kts Java 2 Marks

Uploaded by

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

JAVA PROGRAMMING

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;
}
}
}

//Write a program to draw different shape in Java


import java.applet.*;
import java.awt.*;

public class DrawStuff extends Applet {

int width, height;

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}

public void paint( Graphics g ) {


g.setColor( Color.blue);
g.drawRect( 30, 40, 150, 20 );
g.setColor( Color.pink );
g.fillRect( 240, 160, 40, 110 );

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.

//Write a program of Prime Number in Java

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”);
}
}

//Write a program in Java to reverse the digits


import java.util.Scanner;
class ReverseNumber{
public static void main(String args[])

{
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);

Armstrong Number in Java:


Armstrong number is a number that is equal to the sum of cubes of its digits for example o,
1, 153, 370, 371, 407 etc.
Why 153 is an Armstrong number.
153 = (1*1*1)+(5*5*5)+(3*3*3)

where:
(1*1*1)=1

(5*5*5)=125

(3*3*3)=27

So:
1+125+27=153

Why 371 is an Armstrong number.


371 = (3*3*3)+(7*7*7)+(1*1*1)

where:
(3*3*3)=27

(7*7*7)=343

(1*1*1)=1

So:
27+343+1=371

153, 371, 9474 and 54748 are few Armstrong numbers.


153 = 13 + 53 + 33
371 = 33 +73 +13
9474 = 94 + 44 +74 + 44
54748 = 55 + 45 + 75 + 45 + 85

Java Program to check whether a given number is an Armstrong


number

import java.util.*;

import java.io.*;

class arm
{

public static void main(String arg[])

Scanner ob = new Scanner(System.in);

System.out.println(“Enter any number to check whether it is armstrong or not:”);

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)

System.out.print(“Given number ” + temp +” is Armstrong”);

else

System.out.println(“Given number ” + temp +” is not Armstrong”);

Twisted Prime Number :-


If a number is prime, and its reverse number is also prime, then it is called Twisted prime
number.

For Example :- 37 is prime number , and its reverse order is 73 and 73 is also prime
number.
import java.io.*;

public class twistprime

public static void main(String aa[])throws IOException

InputStreamReader read=new InputStreamReader(System.in);

BufferedReader in=new BufferedReader(read);

int n, r, m, i, j, g; int s=0; int k=0, c=0;

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)

System.out.println(p+” is twisted prime”);

else

System.out.println(p+” is not twisted prime”);

/* Swap Numbers Java Example*/


import java.io.*;
class sw{

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);
//swap the value
swap(num1, num2);
}
private static void swap(int num1, int num2) {

int temp = num1;


num1 = num2;
num2 = temp;

System.out.println(“After Swapping”);
System.out.println(“Value of num1 is :” + num1);
System.out.println(“Value of num2 is :” +num2);

}
}

Palindrome Strings in Java:

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

public static void main(String[] args) throws IOException

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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)

System.out.println(“\nGiven number is a perfect number”);

else

System.out.println(“\nGiven number is not perfect number”);

//Write a program in java to find the sum of the series.


//X=1+1/2+1/3+————+1/10
import java.io.*;
public class ser1
{
public static void main(String aa[])
{
int a;
float x;
x=0;
for(a=1;a<=10;a++)
{
x=x+1/a;
}
System.out.println(“Sum of the series=”+x);
}
}

Binding:
Connecting a method call to the method body is known as binding.There are two types of
binding.

1. Static Binding (also known as early binding).


2. Dynamic Binding (also known as late binding).
1. Static Binding:
It is also known as early binding.It is a compile time operation.When type of the object is
determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.

Overloaded methods are bounded using static binding at compile time.

Static binding example:


class animal

//……….

class cat extends animal

public void walk()

System.out.println(“cat walks”);
}

public static void main( String args[])

cat obj1 = new cat();

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

public void sum(int a)

System.out.println(“int value=”+a);

public void sum(float b)

System.out.println(“float value=”+b);

public void sum(String c)

System.out.println(“String value=”+c);

}
}

class xyz

public static void main(String arg[])

abc a1=new abc();

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.

Dynamic binding example


Here animal is a super class and cat is a child class since cat extends animal. Both these
classes have a same method void walk(). Since we have assigned the parent class reference
to the child class object, during call of walk() method the compiler would not be able to
decide which walk() method to call. It will be confused between the walk() method of animal
class and walk() method of cat class. Such kind of bindings are known as dynamic binding
as compiler figures out the object type in runtime.
class animal

public void walk()


{

System.out.println(“animal walks”);

class cat extends anima

l{

public void walk()

System.out.println(“cat walks”);

public static void main( String args[])

{
//Reference is of parent class
animal obj = new cat();

obj.walk();

Output:
cat walks

Difference between Static and Dyanmic Binding in Java:

Difference between static and dynamic binding is a popular Java programming


interview question which tries to explore candidates knowledge on have compiler
and JVM finds which methods to call if there are more than one method of same name as
it’s case in method overloading and overriding. This is also best way to understand what is
static binding and what is dynamic binding in Java. In next section we will difference
between both of them.

Static Binding Dynamic Binding

It is also known as early Binding. It is also known as Late Binding.


Static binding is a compile time Dynamic binding is a runtime
operation. operation.

Static binding only uses Type


information, and method Dynamic or late binding resolves
resolution is based upon type of method based upon actual
reference variable object.

In Java programming language,


private, static and final method only virtual methods are resolved
are resolved using static binding using dynamic binding.

Overloaded methods are bounded Overridden methods are


using static binding at compile bounded using dynamic
time.e.g. binding.e.g

Class addition { Class animal{

void sum(int a,int b){ class Animal {

System.out.println(a+b);} public void move(){

void sum(int a,int b,int c){ System.out.println(“Animals can


move”);}}
System.out.println(a+b+c);}
class Dog extends Animal {
public static void main(String
args[]) { public void move() {

addition obj=new addition(); System.out.println(“Dogs can


walk and run”);
obj.sum(10,10,10);
obj.sum(20,20); }}

}} public class TestDog {

public static void main(String


args[]) {

Animal a = new Animal(); //


Animal reference and
objectAnimal b = new Dog(); //
Animal reference but Dog
objecta.move();//output: Animals
can move b.move();//output:Dogs
can walk and run

}}

Polymorphism in java is a concept by which we can perform a single action by different


ways. Polymorphism is derived from 2 greek words: poly and morphs. The word “poly”
means many and “morphs” means forms. So polymorphism means many forms.
There are two types of polymorphism in java:

1.Compile time polymorphism


2.Runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding.If
you overload static method in java, it is the example of compile time polymorphism.
1.Compile time polymorphism:
Compile time polymorphism is also known as Static Binding Polymorphism.This is
used to write the program in such a way, that flow of control is decided in compile time
itself. It is achieved using method overloading.Compile time polymorphism is nothing but
the method overloading in java.
In method overloading, an object can have two or more methods with same name, BUT,
with their method parameters different. These parameters may be different on two bases:
1) Parameter type: Type of method parameters can be different.
The actual method to be called is decided on compile time based on parameters passed to
function in program.

class abc

public void sum(int a)

System.out.println(“int value=”+a);

public void sum(float b)

System.out.println(“float value=”+b);

}
public void sum(String c)

System.out.println(“String value=”+c);

class xyz

public static void main(String arg[])

abc a1=new abc();

a1.sum(10);

a1.sum(2.4);

a1.sum(“Ram”);

output:
sum=10

sum=2.7

sum=Ram

2) Parameter count: Functions accepting different number of parameters.e.g.


Lets see the below example to understand it better-

class abc

public void sum(int a)


{

System.out.println(“sum=”+a);

public void sum(int b,int c)

System.out.println(“sum=”+b+”,”+c);

public void sum(int d,int e,int f)

System.out.println(“sum=”+d+”,”+e+”,”+f);

class xyz

public static void main(String arg[])

abc a1=new abc();

a1.sum(10);

a1.sum(10,20);

a1.sum(10,20,30);

output:
sum=10

sum=10,20

sum=10,20,30

2. Runtime Polymorphism in Java:


Runtime polymorphism is also known as Dynamic Binding Polymorphism.It is a
process in which a call to an overridden method is resolved at runtime rather than compile-
time.
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Runtime polymorphism with overriding the method:


The method overriding is an example of runtime polymorphism. You can have a method in
subclass overrides the method in its super classes with the same name and signature. Java
virtual machine determines the proper method to call at the runtime, not at the compile
time.

Let’s take a look at the following example:

class animal{

public void whoru()

System.out.println(“I am a animal.”);

class dog extends animal

{public void whoru()

System.out.println(“I am a dog.”);

}
class goat extends animal

public void whoru( )

System.out.println(“I am a goat.”);

class cat extends animal{public void whoru()

System.out.println(“I am a cat.”);

class RunPoly

public static void main(String aa[])

animal ref1 = new animal();

animal ref2 = new dog();

animal ref3 = new goat();

animal ref4 = new cat();

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.

Runtime polymorphism with super class methods


Super class methods can be overridden in the sub class. If the super class method has to be
called from the sub class method that is overridden, then it can be achieved using
super.methodname. For example, in the above Student class, the printStudent method is
used to print the name and studentId. If the printStudent method is overridden in the
GraduateStudent class to print noOfYears_Course along with name and studentId, then
printStudent method of super class can be called within this overridden method using
super. This scenario is demonstrated below:

class Student

int yearCourse;

public Student(String name, String stuId, int yearCourse)//constructor of the class

super(name, stutId);
this.yearCourse = yearCourse;

}
public void printStudent()

super.printStudent();

System.out.println(“The no of years of the course is:” + Course );

class school

public static void main(String aa[])

student s1=new student(“Ram”,101,2009);

//when object is created the constructor is automatically called

s1.printStudent();

}
In above example:
The printStudent() underlined above is equivalent to:

public void printStudent()

System.out.println(“Name of the person is:” + name);

System.out.println(“Id of the Student is:”+ stuId);

System.out.println(“The student id is:” + stuId);

}
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.

There are 2 ways to set java path:


1. Temporary
2. Permanent
1) How to set Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow following steps:

1. First you create your folder in any drive.


2. Open notepad editor.
3. Write following path.
For Example:
set path=C:\Windows\System32;d:\jdk1.6.0\bin;

4. Then save this file with .bat extension in your folder.

5. Now open command prompt and execute the bat file.

How to set Permanent Path of JDK in Windows


For setting the permanent path of JDK, you need to follow these steps:
• Go to MyComputer properties -> advanced tab -> environment variables -> new tab of
user variable -> write path in variable name -> write path of bin folder in variable value ->
ok -> ok -> ok
For Example:
1)Go to MyComputer properties.

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:

How to create String object?


There are two ways to create String object:

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.

public class Str{


public static void main(String args[]){
char[] hArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String s1 = new String(hArray);
System.out.println(s1);
}}

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.

Why java uses concept of string literal?


To make Java more memory efficient (because no new objects are created if it exists already
in string constant pool).

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 );
}}

You might also like