0% found this document useful (0 votes)
140 views118 pages

Java Tasks 25 10 2018

The document discusses developing Java programs to demonstrate various topics: 1. Develop programs to demonstrate applet and frame life cycles, and mouse and key event handling using applets and frames. 2. Develop a program to create different types of containers in Java. 3. Develop a program that adds menus to a frame, demonstrating how to create menu bars and menus.

Uploaded by

Vds Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views118 pages

Java Tasks 25 10 2018

The document discusses developing Java programs to demonstrate various topics: 1. Develop programs to demonstrate applet and frame life cycles, and mouse and key event handling using applets and frames. 2. Develop a program to create different types of containers in Java. 3. Develop a program that adds menus to a frame, demonstrating how to create menu bars and menus.

Uploaded by

Vds Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

Date : 25 October, 2018

a) Develop a Java Program to demonstrate Applet Life Cycle


b) Develop a Java Program to demonstrate Mouse Event Handling(using
Applet)
c) Develop a Java Program to demonstrate Mouse Event Handling(using
Frame)
d) Develop a Java Program to demonstrate Key Event Handling (using
Applet)
e) Develop a Java Program to demonstrate Key Event Handling (using
Frame)
f) Develop a Java program to create different type of containers
g) Develop a Java Program to menus to a Frame(MenuDemo.java)

N Nagarjuna OOP through Java


A

AWT Packages

AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18
packages of 737 classes as of JDK 8). Fortunately, only 2 packages - java.awt and
java.awt.event - are commonly-used.

1. The java.awt package contains the core AWT graphics classes:


o GUI Component classes, such as Button, TextField, and Label.
o GUI Container classes, such as Frame and Panel.
o Layout managers, such as FlowLayout, BorderLayout and GridLayout.
o Custom graphics classes, such as Graphics, Color and Font.
2. The java.awt.event package supports event handling:
o Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent,
o Event Listener Interfaces, such as ActionListener, MouseListener,
MouseMotionListener, KeyListener and WindowListener,
o Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and
WindowAdapter.

AWT provides a platform-independent and device-independent interface to develop graphic


programs that runs on all platforms, including Windows, Mac OS X, and Unixes.

There are two types of GUI elements:

1. Component: Components are elementary GUI entities, such as Button, Label, and
TextField.
2. Container: Containers, such as Frame and Panel, are used to hold components in a
specific layout (such as FlowLayout or GridLayout). A container can also hold sub-
containers.

In the above figure, there are three containers: a Frame and two Panels. A Frame is the top-
level container of an AWT program. A Frame has a title bar (containing an icon, a title, and
the minimize/maximize/close buttons), an optional menu bar and the content display area. A
Panel is a rectangular area used to group related GUI components in a certain layout. In the
above figure, the top-level Frame contains two Panels. There are five components: a Label

N Nagarjuna OOP through Java


(providing description), a TextField (for users to enter text), and three Buttons (for user to
trigger certain programmed actions).

In a GUI program, a component must be kept in a container. You need to identify a container
to hold the components. Every container has a method called add(Component c). A
container (say c) can invoke c.add(aComponent) to add aComponent into itself. For
example,

Panel pnl = new Panel(); // Panel is a container


Button btn = new Button("Press"); // Button is a component
pnl.add(btn); // The Panel container adds a
Button component

GUI components are also called controls (e.g., Microsoft ActiveX Control), widgets (e.g.,
Eclipse's Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with
(or control) the application.

AWT Container Classes

Top-Level Containers: Frame, Dialog and Applet

Each GUI program has a top-level container. The commonly-used top-level containers in
AWT are Frame, Dialog and Applet:

 A
Frame provides the "main window" for your GUI application. It has a title bar (containing an
icon, a title, the minimize, maximize/restore-down and close buttons), an optional menu
bar, and the content display area. To write a GUI program, we typically start with a subclass
extending from java.awt.Frame to inherit the main window as follows:

N Nagarjuna OOP through Java


Develop a Java Program to menus to a Frame
(MenuDemo.java)
import java.awt.*;

class MenuDemo extends Frame


{
MenuDemo()
{
/* Creating a Menu bar */
MenuBar mBar = new MenuBar();
Frame f = new Frame();
f.setMenuBar(mBar);
f.setVisible(true);
f.setSize(400,400);

/* Creating Menu File */


Menu File = new Menu("File");
MenuItem i1,i2;
File.add(new MenuItem("NEw"));
File.add(new MenuItem("Open"));
mBar.add(File);

/* Creating Menu Help */


Menu help = new Menu("Help");
MenuItem i3,i4;
help.add(new MenuItem("Welcome"));
help.add(new MenuItem("About"));
mBar.add(help);

}
public static void main(String [] args)
{
MenuDemo obj = new MenuDemo();
}

N Nagarjuna OOP through Java


}
Output:

E:\Java\AWT\Nagarjuna>javac MenuDemo.java

E:\Java\AWT\Nagarjuna>java MenuDemo

N Nagarjuna OOP through Java


Date : 11 October, 2018
Thread Synchronization
1. Write a Java program to demonstrate “synchronized” block
2. Write a Java program to demonstrate “synchronized” method
3. Write a Java program to demonstrate to simulate
concurrency(inthread communication) in java (use wait(),notify()
methods)
4. Develop an application to simulate Producer Consumer problem
using multithreading
5. Write a simulation program for the fruit market. The farmer will be
able to produce different types of fruits (apple, orange, grape, and
watermelon), and put them in the market to sell. The market
has limited capacity and farmers have to stand in a queue if
the capacity is exceeded to sell their fruits. Consumers can
come to the market any time and purchase their desired fruits;
and if the fruits they want to buy runs out, they are willing to wait
until the supply of that kind is ready. (Hint: implementing this market
will encounter the producer and consumer problem, and it probably
needs multiple buffers for different kinds of fruits).

Annotations(Built-in annotations)
1. Write a Java program to demonstrate ‘@override’ annotation
@Override – When we want to override a method of Superclass, we should use this
annotation to inform compiler that we are overriding a method. So when superclass
method is removed or changed, compiler will show error message
2. Write a Java program to demonstrate ‘@Deprecated’ annotation
when we want the compiler to know that a method is deprecated, we should use this annotation. Java
recommends that in javadoc, we should provide information for why this method is deprecated and
what is the alternative to use

3. Write a Java program to demonstrate ‘@SuppressWarnings’


annotation
just to tell compiler to ignore specific warnings they produce, for example using raw types in java
generics. It’s retention policy is SOURCE and it gets discarded by compiler.

N Nagarjuna OOP through Java


Annotation Examples
1)@override example
class ParentClass
{
public void displayMethod(String msg){
System.out.println(msg);
}
}
class SubClass extends ParentClass
{
@Override
public void displayMethod(String msg){
System.out.println("Message is: "+ msg);
}
public static void main(String args[]){
SubClass obj = new SubClass();
obj.displayMethod("Hey!!");
}
}
2)@Deprecated example
public class MyDeprecatedExmp {

/**
* @deprecated
* reason for why it was deprecated
*/
@Deprecated
public void showDeprecatedMessage(){
System.out.println("This method is marked as deprecated");
}

public static void main(String a[]){

MyDeprecatedExmp mde = new MyDeprecatedExmp();


mde.showDeprecatedMessage();
}
}
The @Deprecated annotation will be used to inform the compiler to generate a warning
whenever a program uses a method, class, or field with the @Deprecated annotation. It is
good to document the reason with Javadoc @deprecated tag. Make a note of case difference
with @Deprecated and @deprecated. @deprecated is for documentation purpose.
3)@SupressWarnings
public class MyDeprecatedExmp {

@Deprecated

public void showDeprecatedMessage(){

System.out.println("This method is marked as deprecated");

N Nagarjuna OOP through Java


@SuppressWarnings("deprecation")

public static void main(String a[]){

MyDeprecatedExmp mde = new MyDeprecatedExmp();

mde.showDeprecatedMessage();

Incase if you don't want to get any warnings from compiler for the known things, then you
can use @SuppressWarnings annotation. For example, you are calling deprecated method,
and you know that it is deprecated, to avoid compiler warnings, user @SuppressWarnings
annotation.

N Nagarjuna OOP through Java


Interthread Communication

wait, notify and notifyAll in Java


The current thread which invokes these methods on any object should have the object
monitor else it throws java.lang.IllegalMonitorStateException exception.

wait

Object wait methods has three variance, one which waits indefinitely for any other thread to
call notify or notifyAll method on the object to wake up the current thread. Other two
variances puts the current thread in wait for specific amount of time before they wake up.

notify

notify method wakes up only one thread waiting on the object and that thread starts
execution. So if there are multiple threads waiting for an object, this method will wake up
only one of them. The choice of the thread to wake depends on the OS implementation of
thread management.

notifyAll

notifyAll method wakes up all the threads waiting on the object, although which one will
process first depends on the OS implementation.

These methods can be used to implement producer consumer problem where consumer
threads are waiting for the objects in Queue and producer threads put object in queue and
notify the waiting threads.

1. synchronized keyword is used for exclusive accessing.


2. To make a method synchronized, simply add the synchronized keyword to its
declaration. Then no two invocations of synchronized methods on the same object can
interleave with each other.
3. Synchronized statements must specify the object that provides the intrinsic lock.
When synchronized(this) is used, you have to avoid to synchronizing invocations of
other objects' methods.
4. wait() tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).
5. notify() wakes up the first thread that called wait() on the same object.

Example:

Message.java

A java class on which threads will work and call wait and notify methods.

N Nagarjuna OOP through Java


public class Message {
private String msg;

public Message(String str){


this.msg=str;
}

public String getMsg() {


return msg;
}

public void setMsg(String str) {


this.msg=str;
}

Waiter.java

A class that will wait for other threads to invoke notify methods to complete it’s
processing. Notice that Waiter thread is owning monitor on Message object using
synchronized block.
public class Waiter implements Runnable{

private Message msg;

public Waiter(Message m){


this.msg=m;
}

@Override
public void run() {
String name = Thread.currentThread().getName();
synchronized (msg) {
try{
System.out.println(name+" waiting to get notified at
time:"+System.currentTimeMillis());
msg.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name+" waiter thread got notified at
time:"+System.currentTimeMillis());
//process the message now
System.out.println(name+" processed: "+msg.getMsg());
}
}

Notifier.java

N Nagarjuna OOP through Java


A class that will process on Message object and then invoke notify method to wake up
threads waiting for Message object. Notice that synchronized block is used to own the
monitor of Message object.

public class Notifier implements Runnable


{
private Message msg;

public Notifier(Message msg) {


this.msg = msg;
}

@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name+" started");
try {
Thread.sleep(1000);
synchronized (msg) {
msg.setMsg(name+" Notifier work done");
msg.notify();
// msg.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

InterThreadCommunicationDemo
Test class that will create multiple threads of Waiter and Notifier and start them.

public class InterThreadCommunicationDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
Message msg = new Message("process it");
Waiter waiter = new Waiter(msg);
new Thread(waiter,"waiter").start();

Waiter waiter1 = new Waiter(msg);


new Thread(waiter1, "waiter1").start();

Notifier notifier = new Notifier(msg);


new Thread(notifier, "notifier").start();
System.out.println("All the threads are started");

N Nagarjuna OOP through Java


Producer Consumer /Bounded Buffer Problem(Inthread communication)
Inter thread communication

Producer Consumer/Bounded Buffer Problem.

Producer Consumer Problem is well-known example of multi-thread synchronization


problem. It is described as synchronization problem over a fixed size data buffer
implemented as queue being modified by two or more different processes referred as
producers and consumers. For a data buffer, we can have multiple number of producers and
consumers. Producers task is to keep generating data and place it into buffer while
Consumers task is to keep consuming data from buffer. Problem is to ensure that Producers
do not add data into buffer if its full and Consumer do not consumer data if buffer is empty.

For resolving above problem, Producer and Consumer should behave as below.

Producer

1. Check if Buffer is full or not. If full, then wait() for buffer items to get consumed.

2. Generate data and put it into Buffer.

3. Notify Consumer that Data has been placed into Buffer.

N Nagarjuna OOP through Java


4. Repeat step 1-3

Consumer

1. Check if Buffer has items. If empty, then wait() for buffer to get filled.

2. Consume data from Buffer.

3. Notify Producer that Data has been consumed from Buffer

4. Repear step 1-3

Synchronized Instance Methods

A synchronized instance method in Java is synchronized on the instance (object) owning the
method. Thus, each instance has its synchronized methods synchronized on a different object:
the owning instance. Only one thread can execute inside a synchronized instance method.

Example #1
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}

N Nagarjuna OOP through Java


synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable

N Nagarjuna OOP through Java


{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class ProdConsDemo
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
} class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}

N Nagarjuna OOP through Java


catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()

N Nagarjuna OOP through Java


{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
Example #2

N Nagarjuna OOP through Java


import java.util.*;
class Buffer {
private int data;
private boolean empty;

public Buffer()
{
this.empty = true;
}

public synchronized void produce(int newData) {


while (!this.empty) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data = newData;
this.empty = false;
this.notify();
System.out.println("Producer put...:" + newData);
}

public synchronized int consume() {


while (this.empty) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.empty = true;
this.notify();

N Nagarjuna OOP through Java


System.out.println("Consumer get...:" + data);
return data;
}
}
/*Producer */
class Producer extends Thread {
private Buffer buffer;

public Producer(Buffer buffer) {


this.buffer = buffer;
}

public void run() {


Random rand = new Random();
while (true) {
int n = rand.nextInt();
buffer.produce(n);
}
}
}

/*Consumer */
class Consumer extends Thread {
private Buffer buffer;

public Consumer(Buffer buffer) {


this.buffer = buffer;
}

public void run() {


int data;
while (true) {
data = buffer.consume();
}

N Nagarjuna OOP through Java


}
}

public class ProducerConsumer


{
public static void main(String[] args)
{
Buffer buffer = new Buffer();
Producer p = new Producer(buffer);
Consumer c = new Consumer(buffer);

p.start();
c.start();
}
}

Example #2
class BankQueue {
int nextToGive=0, nextToServe=0;
synchronized int nextNumberToCustomer() {
notify();
return ++nextToGive;
}
synchronized int nextToServe() throws InterruptedException{
if (!(nextToServe<nextToGive)){
System.out.println("Waiting");
wait();
}
return ++nextToServe;
}
}

class Consumer implements Runnable{


BankQueue queue;

N Nagarjuna OOP through Java


Consumer(BankQueue queue) { this.queue=queue;}
public void run() {
try {
while (true) {
int n=queue.nextToServe();
System.console().format("Serving customer no: %d\n",n);
}
} catch(InterruptedException e) {}
}
}
class Producer implements Runnable{
BankQueue queue;
Producer(BankQueue queue) { this.queue=queue;}
public void run() {
while (true) {
int n=queue.nextNumberToCustomer();
System.console().format("New customer no: %d\n",n);
}
}
}
class ProducerConsumerBank {
public static void main(String[] args) {
int numConsumers=10, numProducers=2;
BankQueue theQueue=new BankQueue();
for(int i=0;i<numConsumers;i++)
new Thread(new Consumer(theQueue)).start();
for(int i=0;i<numProducers;i++)
new Thread(new Producer(theQueue)).start();
}
}

N Nagarjuna OOP through Java


Java Annotations
Java Annotations allow us to add metadata information into our source code,
although they are not a part of the program itself. Annotations were added to
the java from JDK 5. Annotation has no direct effect on the operation of the code
they annotate (i.e. it does not affect the execution of the program).

What’s the use of Annotations?


1) Instructions to the compiler: There are three built-in annotations available in Java
(@Deprecated, @Override & @SuppressWarnings) that can be used for giving certain
instructions to the compiler. For example the @override annotation is used for instructing
compiler that the annotated method is overriding the method. More about these built-in
annotations with example is discussed in the next sections of this article.

2) Compile-time instructors: Annotations can provide compile-time instructions to the


compiler that can be further used by sofware build tools for generating code, XML files etc.

3) Runtime instructions: We can define annotations to be available at runtime which we can access
using java reflection and can be used to give instructions to the program at runtime.

Annotations basics
An annotation always starts with the symbol @ followed by the annotation name. The symbol
@ indicates to the compiler that this is an annotation.

For e.g. @Override


Here @ symbol represents that this is an annotation and the Override is the name of this
annotation.

Where we can use annotations?


Annotations can be applied to the classes, interfaces, methods and fields. For example the
below annotation is being applied to the method.

@Override
void myMethod() {
//Do something
}

What this annotation is exactly doing here is explained in the next section but to be brief it is
instructing compiler that myMethod() is a overriding method which is overriding the method
(myMethod()) of super class.

Built-in Annotations in Java


Java has three built-in annotations:

N Nagarjuna OOP through Java


 @Override
 @Deprecated
 @SuppressWarnings

1) @Override:

While overriding a method in the child class, we should use this annotation to mark that
method. This makes code readable and avoid maintenance issues, such as: while changing the
method signature of parent class, you must change the signature in child classes (where this
annotation is being used) otherwise compiler would throw compilation error. This is difficult
to trace when you haven’t used this annotation.

Example:

public class MyParentClass {

public void justaMethod() {


System.out.println("Parent class method");
}
}

public class MyChildClass extends MyParentClass {

@Override
public void justaMethod() {
System.out.println("Child class method");
}
}

I believe the example is self explanatory. To read more about this annotation, refer this
article: @Override built-in annotation.

2) @Deprecated

@Deprecated annotation indicates that the marked element (class, method or field) is
deprecated and should no longer be used. The compiler generates a warning whenever a
program uses a method, class, or field that has already been marked with the @Deprecated
annotation. When an element is deprecated, it should also be documented using the Javadoc
@deprecated tag, as shown in the following example. Make a note of case difference with
@Deprecated and @deprecated. @deprecated is used for documentation purpose.

Example:

/**
* @deprecated
* reason for why it was deprecated
*/
@Deprecated
public void anyMethodHere(){
// Do something
}

N Nagarjuna OOP through Java


Now, whenever any program would use this method, the compiler would generate a warning.
To read more about this annotation, refer this article: Java – @Deprecated annotation.

3) @SuppressWarnings

This annotation instructs compiler to ignore specific warnings. For example in the below
code, I am calling a deprecated method (lets assume that the method deprecatedMethod() is
marked with @Deprecated annotation) so the compiler should generate a warning, however I
am using @@SuppressWarnings annotation that would suppress that deprecation warning.

@SuppressWarnings("deprecation")
void myMethod() {
myObject.deprecatedMethod();
}

N Nagarjuna OOP through Java


Date : 04 October, 2018
1. Write a Java program to demonstrate different ways of creating threads
2. Write a Java program to demonstrate various thread methods(getName( ),
setName( ),getId( ),currentThread( ),isAlive( ),join( ),isDaemon( ),start( ),run( ),
getState( ), isInterrrupted (),sleep( ))
3. Write a Java program to demonstrate priority of threads
4. Write a Java program that creates two threads.One thread displays “CSE
Thread” dor every 2 seconds and other thread displays “CVR Thread” for
every 2 seconds.
5. Write a Java program that creates two threads.One thread will print even
numbers and other thread will print odd numbers
6. Write a Java program to input a word from the user and remove the duplicate
characters present in it.

 Example:
 INPUT – abcabcabc
OUTPUT – abc
 INPUT – javaforschool
OUTPUT – javforschl
 INPUT – Mississippi
OUTPUT – Misp
7. Write a Java program to write a java program to create a StringBuffer object
and illustrate the following operation
 How to append character.
 Insert character at the beginning.
 Operation of reverse () method.
 Conversion string to number.
 Converting Numbers to Strings
 Getting Characters and Substrings by Index
 Searching for Characters and Substrings in a String
 Replacing Characters and Substrings into a String
 Comparing Strings and Portions of Strings
 Display the capacity and lent of the string buffer.

8. Write a Java program to swaps the values of two Strings without using any
third (temp) variable.

N Nagarjuna OOP through Java


Method Description

setName() to give thread a name

getName() return thread's name

getPriority() return thread's priority

isAlive() checks if thread is still running or not

join() Wait for a thread to end

run() Entry point for a thread

sleep() suspend thread for a specified time

start() start a thread by calling run() method

Some Important points to Remember

1. When we extend Thread class, we cannot override setName() and


getName() functions, because they are declared final in Thread class.
2. While using sleep(), always handle the exception it throws.

static void sleep(long milliseconds) throws InterruptedException

N Nagarjuna OOP through Java


Date : 27 September, 2018
String class and StringBuffer class methods
1. Write a Java program to get the character at the given index within the
String

2. Write a Java program to concatenate a given string to the end of another


string

3. Write a java program to compare two strings lexicographically

4. Write a Java program to test if a given string contains the specified


sequence of char values.

5. Write a Java program to check whether two String objects contain the
same data.

6. Write a Java program to compare a given string to the specified character


sequence

7. Write a Java program to compare a given string to another string,


ignoring case considerations.

8. Write a java program to count number of words in string

9. Write a java program to demonstrate

Given a string, return a new string where the first and last
chars have been exchanged.

frontBack("code") → "eodc"

frontBack("a") → "a"

frontBack("ab") → "ba"
10.Write a java program to demonstrate

Given a string, take the last char and return a new string with the
last char added at the front and back, so "cat" yields "tcatt". The
original string will be length 1 or more.

backAround("cat") → "tcatt"

backAround("Hello") → "oHelloo"

backAround("a") → "aaa"

N Nagarjuna OOP through Java


11.Write a java program

Given a string, return a new string where the last 3 chars are
now in upper case. If the string has less than 3 chars,
uppercase whatever is there.
12.Write a java program to divide a string into „n‟ equal parts

13.Write a java program to find first non repeating character in a string

14.Write a java program to find repeated and non-repeated characters.

15.Write a java program to find vowels with their frequency in a given string.

16.Write a java program find character frequencies from the given string

17.Write a java program to find reverse of a string.

N Nagarjuna OOP through Java


Using contains() and trim() method
Having finished most of our application for the fair, it's time to focus on minor details that
went wrong during a test run of our application in this module. Accidentally some gibberish
text with leading and trailing got copied to the clipboard and got pasted in the some of your
text documents. Don't worry, still, we have the gibberish text with us, you can manually load
each document, and find the text and delete it. Think it will take ages, no we can think of a
time saver. Using your programming skills, load each document in a program and find in
which files the text got copied. Assume text of the document is given as the input to the
program. write a program to find whether the gibberish text is present in the string.

Create a driver class called Main. In the Main method, obtain the inputs from the console
(Refer I/O) and prompt whether the gibberish text is present in the main text.

[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input/output 1:

Enter the text from the document


One fine morning, a minister from Emperor Akbar's court had gathered in the
assembly hall.He informed the Emperor that all his valuables had been stolen by a thief
the previous night.
Enter the string to be found in the data
stolen
String is found in the document

Sample Input/output 2:

Enter the text from the document


One fine morning, a minister from Emperor Akbar's court had gathered in the
assembly hall.He informed the Emperor that all his valuables had been stolen by a thief
the previous night.
Enter the string to be found in the data
Birbal
String is not found in the document

Problem Requirements:

Java
Keyword Min Count Max Count

trim 1 -

Keyword Min Count Max Count

contains 1 -

N Nagarjuna OOP through Java


StringBuilder /StringBuffer
Given a code, try to change the code to expected format. The first 2 letters correspond to the city
code, DH - Delhi MB - Mumbai KL - Kolkata. The digits following the city code correspond to the
reference number. In the output code, the city code changes as given below.
DH - DEL
MB - MUM
KL - KOL

Also, need to maintain uniformity in the number of digits in the reference number be 5 digits.
Create a driver class called Main. In the Main method, obtain the input from the console and print
the formatted code.
Note: Use StringBuilder

[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input/Output 1:
Enter the code
DH1
Formatted code
DEL00001

Sample Input/Output 2:

Enter the code


MB12345
Formatted code
MUB12345

Problem Requirements:

Java
Keyword Min Count Max Count

StringBuilder 1 -

Keyword Min Count Max Count

substring 1 -

Keyword Min Count Max Count

replace 1 -

N Nagarjuna OOP through Java


Strings
What are Strings?
A string in literal terms is a series of characters. Hey, did you say characters, isn’t it a
primitive data type in Java. Yes, so in technical terms, the basic Java String is basically an
array of characters.

So my above string of “ROSE” can be represented as the following –

In this tutorial, you will learn-

 What are Strings?


 Why use Strings?
 String Syntax Examples
 String Concatenation
 Important Java string methods

Why use Strings?


One of the primary functions of modern computer science, is processing human language.

Similarly to how numbers are important to math, language symbols are important to meaning
and decision making. Although it may not be visible to computer users, computers process
language in the background as precisely and accurately as a calculator. Help dialogs provide
instructions. Menus provide choices. And data displays show statuses, errors, and real-time
changes to the language.

As a Java programmer, one of your main tools for storing and processing language is going to
be the String class.

String Syntax Examples


Now, let’s get to some syntax,after all, we need to write this in Java code isn’t it.

String is an array of characters, represented as:

N Nagarjuna OOP through Java


//String is an array of characters
char[] arrSample = {'R', 'O', 'S', 'E'};
String strSample_1 = new String (arrSample);

In technical terms, the String is defined as follows in the above example-

= new (argument);

Now we always cannot write our strings as arrays; hence we can define the String in Java as
follows:

//Representation of String
String strSample_2 = "ROSE";

In technical terms, the above is represented as:

= ;

The String Class Java extends the Object class.

String Concatenation:
Concatenation is joining of two or more strings.

Have a look at the below picture-

We have two strings str1 = “Rock” and str2 = “Star”

If we add up these two strings, we should have a result as str3= “RockStar”.

Check the below code snippet,and it explains the two methods to perform string
concatenation.

N Nagarjuna OOP through Java


First is using “concat” method of String class and second is using arithmetic “+” operator.
Both results in the same output

public class Sample_String{


public static void main(String[] args){
//String Concatenation
String str1 = "Rock";
String str2 = "Star";
//Method 1 : Using concat
String str3 = str1.concat(str2);
System.out.println(str3);
//Method 2 : Using "+" operator
String str4 = str1 + str2;
System.out.println(str4);
}
}

Important Java string methods :

Let’s ask the Java String class a few questions and see if it can answer them ;)

String "Length" Method

How will you determine the length of given String? I have provided a method called as
“length”. Use it against the String you need to find the length.

public class Sample_String{


public static void main(String[] args){ //Our sample string for this
tutorial
String str_Sample = "RockStar";
//Length of a String

N Nagarjuna OOP through Java


System.out.println("Length of String: " + str_Sample.length());}}

output:

Length of String: 8

String "indexOf" Method

If I know the length, how would I find which character is in which position? In short, how
will I find the index of a character?

You answered yourself, buddy, there is an “indexOf” method that will help you determine the
location of a specific character that you specify.

public class Sample_String{


public static void main(String[] args){//Character at position
String str_Sample = "RockStar";
System.out.println("Character at position 5: " + str_Sample.charAt(5));
//Index of a given character
System.out.println("Index of character 'S': " + str_Sample.indexOf('S'));}}

Output:

Character at position 5: t
Index of character 'S': 4

String "charAt" Method

Similar to the above question, given the index, how do I know the character at that location?

Simple one again!! Use the “charAt” method and provide the index whose character you need
to find.

public class Sample_String{


public static void main(String[] args){//Character at position
String str_Sample = "RockStar";
System.out.println("Character at position 5: " + str_Sample.charAt(5));}}

Output:

Character at position 5: t

String "CompareTo" Method

Do I want to check if the String that was generated by some method is equal to something
that I want to verify with? How do I compare two Strings?

Use the method “compareTo” and specify the String that you would like to compare.

Use “compareToIgnoreCase” in case you don’t want the result to be case sensitive.

N Nagarjuna OOP through Java


The result will have the value 0 if the argument string is equal to this string; a value less than
0 if this string is lexicographically less than the string argument; and a value greater than 0 if
this string is lexicographically greater than the string argument.

public class Sample_String{


public static void main(String[] args){//Compare to a String
String str_Sample = "RockStar";
System.out.println("Compare To 'ROCKSTAR': " +
str_Sample.compareTo("rockstar"));
//Compare to - Ignore case
System.out.println("Compare To 'ROCKSTAR' - Case Ignored: " +
str_Sample.compareToIgnoreCase("ROCKSTAR"));}}

Output:

Compare To 'ROCKSTAR': -32


Compare To 'ROCKSTAR' - Case Ignored: 0

String "Contain" Method

I partially know what the string should have contained, how do I confirm if the String
contains a sequence of characters I specify?

Use the method “contains” and specify the characters you need to check.

Returns true if and only if this string contains the specified sequence of char values.

public class Sample_String{


public static void main(String[] args){ //Check if String contains a
sequence
String str_Sample = "RockStar";
System.out.println("Contains sequence 'tar': " +
str_Sample.contains("tar"));}}

Output:

Contains sequence 'tar': true

String "endsWith" Method

How do I confirm if a String ends with a particular suffix? Again you answered it. Use the
“endsWith” method and specify the suffix in the arguments.

Returns true if the character sequence represented by the argument is a suffix of the character
sequence represented by this object.

public class Sample_String{


public static void main(String[] args){ //Check if ends with a
particular sequence
String str_Sample = "RockStar";
System.out.println("EndsWith character 'r': " +
str_Sample.endsWith("r"));}}

Output:

N Nagarjuna OOP through Java


EndsWith character 'r': true

String "replaceAll" & "replaceFirst" Method

I want to modify my String at several places and replace several parts of the String?

Java String Replace, replaceAll and replaceFirst methods. You can specify the part of the String you
want to replace and the replacement String in the arguments.

public class Sample_String{


public static void main(String[] args){//Replace Rock with the word Duke
String str_Sample = "RockStar";
System.out.println("Replace 'Rock' with 'Duke': " +
str_Sample.replace("Rock", "Duke"));}}

Output:

Replace 'Rock' with 'Duke': DukeStar

String Java "tolowercase" & Java "touppercase" Method

I want my entire String to be shown in lower case or Uppercase?

Just use the “toLowercase()” or “ToUpperCase()” methods against the Strings that need to be
converted.

public class Sample_String{


public static void main(String[] args){//Convert to LowerCase
String str_Sample = "RockStar";
System.out.println("Convert to LowerCase: " + str_Sample.toLowerCase());
//Convert to UpperCase
System.out.println("Convert to UpperCase: " + str_Sample.toUpperCase());}}

Output:

Convert to LowerCase: rockstar


Convert to UpperCase: ROCKSTAR

Important Points to Note:


 String is a Final class; i.e once created the value cannot be altered. Thus String objects are
called immutable.
 The Java Virtual Machine(JVM) creates a memory location especially for Strings called String
Constant Pool. That’s why String can be initialized without ‘new’ keyword.
 String class falls under java.lang.String hierarchy. But there is no need to import this class.
Java platform provides them automatically.
 String reference can be overridden but that does not delete the content; i.e., if

String h1 = "hello";

h1 = "hello"+"world";

N Nagarjuna OOP through Java


then "hello" String does not get deleted. It just loses its handle.

 Multiple references can be used for same String but it will occur in the same place; i.e., if

String h1 = "hello";

String h2 = "hello";

String h3 = "hello";

then only one pool for String “hello” is created in the memory with 3 references-h1,h2,h3

 If a number is quoted in “ ” then it becomes a string, not a number anymore. That means if

String S1 ="The number is: "+ "123"+"456";

System.out.println(S1);

then it will print: The number is: 123456

If the initialization is like this:

String S1 = "The number is: "+(123+456);

System.out.println(S1);

then it will print: The number is:579 That's all to Strings!

N Nagarjuna OOP through Java


Java StringBuffer class
StringBuffer

Name
StringBuffer

Synopsis
Class Name:

java.lang.StringBuffer

Superclass:

java.lang.Object

Immediate Subclasses:

None

Interfaces Implemented:

java.io.Serializable

Availability:

JDK 1.0 or later

Description
The StringBuffer class represents a variable-length sequence of characters. StringBuffer
objects are used in computations that involve creating new String objects. The
StringBuffer class provides a number of utility methods for working with StringBuffer
objects, including append() and insert() methods that add characters to a StringBuffer
and methods that fetch the contents of StringBuffer objects.

When a StringBuffer object is created, the constructor determines the initial contents and
capacity of the StringBuffer. The capacity of a StringBuffer is the number of characters
that its internal data structure can hold. This is distinct from the length of the contents of a
StringBuffer, which is the number of characters that are actually stored in the
StringBuffer object. The capacity of a StringBuffer can vary. When a StringBuffer
object is asked to hold more characters than its current capacity allows, the StringBuffer
enlarges its internal data structure. However, it is more costly in terms of execution time and

N Nagarjuna OOP through Java


memory when a StringBuffer has to repeatedly increase its capacity than when a
StringBuffer object is created with sufficient capacity.

Because the intended use of StringBuffer objects involves modifying their contents, all
methods of the StringBuffer class that modify StringBuffer objects are synchronized.
This means that is it safe for multiple threads to try to modify a StringBuffer object at the
same time.

StringBuffer objects are used implicitly by the string concatenation operator. Consider the
following code:

String s, s1, s2;


s = s1 + s2;

To compute the string concatenation, the Java compiler generates code like:

s = new StringBuffer().append(s1).append(s2).toString();

Class Summary
public class java.lang.StringBuffer extends java.lang.Object {
// Constructors
public StringBuffer();
public StringBuffer(int length);
public StringBuffer(String str);
// Instance Methods
public StringBuffer append(boolean b);
public synchronized StringBuffer append(char c);
public synchronized StringBuffer append(char[] str);
public synchronized StringBuffer append(char[] str, int offset, int
len);
public StringBuffer append(double d);
public StringBuffer append(float f);
public StringBuffer append(int i);
public StringBuffer append(long l);
public synchronized StringBuffer append(Object obj);
public synchronized StringBuffer append(String str);
public int capacity();
public synchronized char charAt(int index);
public synchronized void ensureCapacity(int minimumCapacity);
public synchronized void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin);
public StringBuffer insert(int offset, boolean b);
public synchronized StringBuffer insert(int offset, char c);
public synchronized StringBuffer insert(int offset, char[] str);
public StringBuffer insert(int offset, double d);
public StringBuffer insert(int offset, float f);
public StringBuffer insert(int offset, int i);
public StringBuffer insert(int offset, long l);
public synchronized StringBuffer insert(int offset, Object obj);
public synchronized StringBuffer insert(int offset, String str);
public int length();
public synchronized StringBuffer reverse();
public synchronized void setCharAt(int index, char ch);
public synchronized void setLength(int newLength);
public String toString();

N Nagarjuna OOP through Java


}

Constructors
StringBuffer
public StringBuffer()
Description

Creates a StringBuffer object that does not contain any characters and has a
capacity of 16 characters.

public StringBuffer(int capacity)


Parameters

capacity

The initial capacity of this StringBufffer object.

Throws

NegativeArraySizeException

If capacity is negative.

Description

Creates a StringBuffer object that does not contain any characters and has the
specified capacity.

public StringBuffer(String str)


Parameters

str

A String object.

Description

Creates a StringBuffer object that contains the same sequence of characters as the
given String object and has a capacity 16 greater than the length of the String.

Instance Methods
append
public StringBuffer append(boolean b)
Parameters

N Nagarjuna OOP through Java


b

A boolean value.

Returns

This StringBuffer object.

Description

This method appends either "true" or "false" to the end of the sequence of
characters stored in ths StringBuffer object, depending on the value of b.

public synchronized StringBuffer append(char c)


Parameters

A char value.

Returns

This StringBuffer object.

Description

This method appends the given character to the end of the sequence of characters
stored in this StringBuffer object.

public synchronized StringBuffer append(char str[])


Parameters

str

An array of char values.

Returns

This StringBuffer object.

Description

This method appends the characters in the given array to the end of the sequence of
characters stored in this StringBuffer object.

public synchronized StringBuffer append(char str[], int offset, int len)


Parameters

str

N Nagarjuna OOP through Java


An array of char values.

offset

An offset into the array.

len

The number of characters from the array to be appended.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset or len are out of range.

Description

This method appends the specified portion of the given array to the end of the
character sequence stored in this StringBuffer object. The portion of the array that
is appended starts offset elements from the beginning of the array and is len
elements long.

public StringBuffer append(double d)


Parameters

A double value.

Returns

This StringBuffer object.

Description

This method converts the given double value to a string using Double.toString(d)
and appends the resulting string to the end of the sequence of characters stored in this
StringBuffer object.

public StringBuffer append(float f)


Parameters

N Nagarjuna OOP through Java


A float value.

Returns

This StringBuffer object.

Description

This method converts the given float value to a string using Float.toString(f)
and appends the resulting string to the end of the sequence of characters stored in this
StringBuffer object.

public StringBuffer append(int i)


Parameters

An int value.

Returns

This StringBuffer object.

Description

This method converts the given int value to a string using Integer.toString(i)
and appends the resulting string to the end of the sequence of characters stored in this
StringBuffer object.

public StringBuffer append(long l)


Parameters

A long value.

Returns

This StringBuffer object.

Description

This method converts the given long value to a string using Long.toString(l) and
appends the resulting string to the end of the sequence of characters stored in this
StringBuffer object.

public synchronized StringBuffer append(Object obj)


Parameters

N Nagarjuna OOP through Java


obj

A reference to an object.

Returns

This StringBuffer object.

Description

This method gets the string representation of the given object by calling
String.valueOf(obj) and appends the resulting string to the end of the character
sequence stored in this StringBuffer object.

public synchronized StringBuffer append(String str)


Parameters

str

A String object.

Returns

This StringBuffer object.

Description

This method appends the sequence of characters represented by the given String to
the characters in this StringBuffer object. If str is null, the string "null" is
appended.

capacity
public int capacity()
Returns

The capacity of this StringBuffer object.

Description

This method returns the current capacity of this object. The capacity of a
StringBuffer object is the number of characters that its internal data structure can
hold. A StringBuffer object automatically increases its capacity when it is asked to
hold more characters than its current capacity allows.

charAt

N Nagarjuna OOP through Java


public synchronized char charAt(int index)
Parameters

index

An index into the StringBuffer.

Returns

The character stored at the specified position in this StringBuffer object.

Throws

StringIndexOutOfBoundsException

If index is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method returns the character at the specified position in the StringBuffer
object. The first character in the StringBuffer is at index 0.

ensureCapacity
public synchronized void ensureCapacity(int minimumCapacity)
Parameters

minimumCapacity

The minimum desired capacity.

Description

This method ensures that the capacity of this StringBuffer object is at least the
specified number of characters. If necessary, the capacity of this object is increased to
the greater of minimumCapacity or double its current capacity plus two.

It is more efficient to ensure that the capacity of a StringBuffer object is sufficient


to hold all of the additions that will be made to its contents, rather than let the
StringBuffer increase its capacity in multiple increments.

getChars
public synchronized void getChars(int srcBegin, int srcEnd, char dst[],
int dstBegin)
Parameters

srcBegin

N Nagarjuna OOP through Java


The index of the first character to be copied.

srcEnd

The index after the last character to be copied.

dst

The destination char array.

dstBegin

An offset into the destination array.

Throws

StringIndexOutOfBoundsException

If srcBegin, srcEnd, or dstBegin is out of range.

Description

This method copies each character in the specified range of this StringBuffer object
to the given array of char values. More specifically, the first character to be copied is
at index srcBegin; the last character to be copied is at index srcEnd-1.

These characters are copied into dst, starting at index dstBegin and ending at index:

dstBegin + (srcEnd-srcBegin) - 1

insert

public StringBuffer insert(int offset, boolean b)


Parameters

offset

An offset into the StringBuffer.

A boolean value.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

N Nagarjuna OOP through Java


If offset is out of range.

Description

This method inserts either "true" or "false" into the sequence of characters stored
in this StringBuffer object, depending on the value of b. The string is inserted at a
position offset characters from the beginning of the sequence. If offset is 0, the
string is inserted before the first character in the StringBuffer.

public synchronized StringBuffer insert(int offset, char c)


Parameters

offset

An offset into the StringBuffer.

A char value.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method inserts the given character into the sequence of characters stored in this
StringBuffer object. The character is inserted at a position offset characters from
the beginning of the sequence. If offset is 0, the character is inserted before the first
character in the StringBuffer.

public synchronized StringBuffer insert(int offset, char str[])


Parameters

offset

An offset into the StringBuffer.

str

An array of char values.

N Nagarjuna OOP through Java


Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method inserts the characters in the given array into the sequence of characters
stored in this StringBuffer object. The characters are inserted at a position offset
characters from the beginning of the sequence. If offset is 0, the characters are
inserted before the first character in the StringBuffer.

public StringBuffer insert(int offset, double d)


Parameters

offset

An offset into the StringBuffer.

A double value.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method converts the given double value to a string using Double.toString(d)
and inserts the resulting string into the sequence of characters stored in this
StringBuffer object. The string is inserted at a position offset characters from the
beginning of the sequence. If offset is 0, the string is inserted before the first
character in the StringBuffer.

N Nagarjuna OOP through Java


public StringBuffer insert(int offset, float f)
Parameters

offset

An offset into the StringBuffer.

A float value.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method converts the given float value to a string using Float.toString(f)
and inserts the resulting string into the sequence of characters stored in this
StringBuffer object. The string is inserted at a position offset characters from the
beginning of the sequence. If offset is 0, the string is inserted before the first
character in the StringBuffer.

public StringBuffer insert(int offset, int i)


Parameters

offset

An offset into the StringBuffer.

An int value.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

N Nagarjuna OOP through Java


If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method converts the given int value to a string using Integer.toString(i)
and inserts the resulting string into the sequence of characters stored in this
StringBuffer object. The string is inserted at a position offset characters from the
beginning of the sequence. If offset is 0, the string is inserted before the first
character in the StringBuffer.

public StringBuffer insert(int offset, long l)


Parameters

offset

An offset into the StringBuffer.

A long value.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method converts the given long value to a string using Long.toString(l) and
inserts the resulting string into the sequence of characters stored in this StringBuffer
object. The string is inserted at a position offset characters from the beginning of the
sequence. If offset is 0, the string is inserted before the first character in the
StringBuffer.

public synchronized StringBuffer insert(int offset, Object obj)


Parameters

offset

An offset into the StringBuffer.

obj

N Nagarjuna OOP through Java


A reference to an object.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method gets the string representation of the given object by calling
String.valueOf(obj) and inserts the resulting string into the sequence of characters
stored in this StringBuffer object. The string is inserted at a position offset
characters from the beginning of the sequence. If offset is 0, the string is inserted
before the first character in the StringBuffer.

public synchronized StringBuffer insert(int offset, String str)


Parameters

offset

An offset into the StringBuffer.

str

A String object.

Returns

This StringBuffer object.

Throws

StringIndexOutOfBoundsException

If offset is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

This method inserts the sequence of characters represented by the given String into
the sequence of characters stored in this StringBuffer object. If str is null, the
string "null" is inserted. The string is inserted at a position offset characters from

N Nagarjuna OOP through Java


the beginning of the sequence. If offset is 0, the string is inserted before the first
character in the StringBuffer.

length
public int length()
Returns

The number of characters stored in this StringBuffer object.

Description

This method returns the number of characters stored in this StringBuffer object.
The length is distinct from the capacity of a StringBuffer, which is the number of
characters that its internal data structure can hold.

reverse
public synchronized StringBuffer reverse()
Returns

This StringBuffer object.

Description

This method reverses the sequence of characters stored in this StringBuffer object.

setCharAt
public synchronized void setCharAt(int index, char ch)
Parameters

index

The index of the character to be set.

ch

A char value.

Throws

StringIndexOutOfBoundsException

If index is less than zero or greater than or equal to the length of the StringBuffer
object.

Description

N Nagarjuna OOP through Java


This method modifies the character located index characters from the beginning of
the sequence of characters stored in this StringBuffer object. The current character
at this position is replaced by the character ch.

setLength
public synchronized void setLength(int newLength)
Parameters

newLength

The new length for this StringBuffer.

Throws

StringIndexOutOfBoundsException

If index is less than zero.

Description

This method sets the length of the sequence of characters stored in this StringBuffer
object. If the length is set to be less than the current length, characters are lost from
the end of the character sequence. If the length is set to be more than the current
length, NUL characters (\u0000) are added to the end of the character sequence.

toString
public String toString()
Returns

A new String object that represents the same sequence of characters as the sequence
of characters stored in this StringBuffer object.

Overrides

Object.toString()

Description

This method returns a new String object that represents the same sequence of
characters as the sequence of characters stored in this StringBuffer object. Note that
any subsequent changes to the contents of this StringBuffer object do not affect the
contents of the String object created by this method.

Inherited Methods
Method Inherited From Method Inherited From

N Nagarjuna OOP through Java


clone() Object equals(Object) Object
finalize() Object getClass() Object
hashCode() Object notify() Object
notifyAll() Object wait() Object
wait(long) Object wait(long, int) Object

N Nagarjuna OOP through Java


Date : 20 September, 2018
Interfaces

1. Develop a Java program to findout area and perimeter of circle


using abstract class.
2. Develop a Java program to findout area and perimeter of square,
rectangle and triangle using
i) Using interfaces and method overloading
ii) Using interfaces and method overriding

Packages

3. Write a Java program to whether the given number id palindrome or


not using packages.
4. Write a Java program to findout gcm and lcm using packages.
Exception Handling

5. Write a Java program to detect and resolve divide-by-zero error

using exception handling

6. Write a Java program to illustrate ArithmeticException,


ArrayIndexOutOfBoundsException, NegativeArraySizeException
using nested try block with suitable example.
7. Write a Java program to create user defined exception(s) and check
whether the entered number is prime or not,palindrome or not,
Even or odd

N Nagarjuna OOP through Java


N Nagarjuna OOP through Java
Date : 06 September, 2018
1. Demonstrate how to create userdefined packages in java and how
to access them
2. Develop Java programs to demonstrate access protection
mechanism within and outside package using
 private
 public
 default/no access modifier
 protected
3. Demonstrate how to create sub-packages and how to access them

N Nagarjuna OOP through Java


Access Modifiers in Java

Access modifiers are those which are applied before data members or methods of a class.
These are used to where to access and where not to access the data members or methods. In
Java programming these are classified into four types:

 Private
 Default (not a keyword)
 Protected
 Public

Note: Default is not a keyword (like public, private, protected are keyword)

If we are not using private, protected and public keywords, then JVM is by default taking as
default access modifiers.

Access modifiers are always used for, how to reuse the features within the package and
access the package between class to class, interface to interface and interface to a class.
Access modifiers provide features accessing and controlling mechanism among the classes
and interfaces.

Note: Protected members of the class are accessible within the same class and another class
of same package and also accessible in inherited class of another package.

Rules for access modifiers:


The following diagram gives rules for Access modifiers.

N Nagarjuna OOP through Java


private: Private members of class in not accessible anywhere in program these are only
accessible within the class. Private are also called class level access modifiers.

Example
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}

public class Demo


{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a); //Compile Time Error, you can't access private
data
obj.show(); //Compile Time Error, you can't access private methods
}
}

public: Public members of any class are accessible anywhere in the program in the same
class and outside of class, within the same package and outside of the package. Public are
also called universal access modifiers.

Example
class Hello
{
public int a=20;

N Nagarjuna OOP through Java


public void show()
{
System.out.println("Hello java");
}
}

public class Demo


{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a);
obj.show();
}
}

Output
20
Hello Java

protected: Protected members of the class are accessible within the same class and another
class of the same package and also accessible in inherited class of another package. Protected
are also called derived level access modifiers.

In below the example we have created two packages pack1 and pack2. In pack1, class A is
public so we can access this class outside of pack1 but method show is declared as a
protected so it is only accessible outside of package pack1 only through inheritance.

Example
// save A.java
package pack1;
public class A
{
protected void show()
{
System.out.println("Hello Java");
}
}
//save B.java
package pack2;
import pack1.*;

class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.show();
}
}

Output
Hello Java

N Nagarjuna OOP through Java


default: Default members of the class are accessible only within the same class and another
class of the same package. The default are also called package level access modifiers.

Example
//save by A.java
package pack;
class A
{
void show()
{
System.out.println("Hello Java");
}
}
//save by B.java
package pack2;
import pack1.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside the package
obj.show(); //Compile Time Error, can't access outside the package
}
}

Output
Hello Java

Note: private access modifier is also known as native access modifier, default access
modifier is also known as package access modifier, protected access modifier is also known
as an inherited access modifier, public access modifier is also known as universal access
modifier.

N Nagarjuna OOP through Java


Package in Java
A package is a collection of similar types of classes, interfaces and sub-packages.

Purpose of package
The purpose of package concept is to provide common classes and interfaces for any program
separately. In other words if we want to develop any class or interface which is common for
most of the java programs than such common classes and interfaces must be place in a
package.

Packages in Java are the way to organize files when a project has many modules. Same like
we organized our files in Computer. For example we store all movies in one folder and songs
in other folder, here also we store same type of files in a particular package for example in
awt package have all classes and interfaces for design GUI components.

N Nagarjuna OOP through Java


Advantage of package
 Package is used to categorize the classes and interfaces so that they can be easily
maintained
 Application development time is less, because reuse the code
 Application memory space is less (main memory)
 Application execution time is less
 Application performance is enhance (improve)
 Redundancy (repetition) of code is minimized
 Package provides access protection.
 Package removes naming collision.

Type of package
Package are classified into two type which are given below.

1. Predefined or built-in package


2. User defined package

Predefined or built-in package


These are the package which are already designed by the Sun Microsystem and supply as a
part of java API, every predefined package is collection of predefined classes, interfaces and
sub-package.

User defined package

N Nagarjuna OOP through Java


If any package is design by the user is known as user defined package. User defined package
are those which are developed by java programmer and supply as a part of their project to
deal with common requirement.

Rules to create user defined package


 package statement should be the first statement of any package program.
 Choose an appropriate class name or interface name and whose modifier must be public.
 Any package program can contain only one public class or only one public interface but it
can contain any number of normal classes.
 Package program should not contain any main class (that means it should not contain any
main())
 modifier of constructor of the class which is present in the package must be public. (This is
not applicable in case of interface because interface have no constructor.)
 The modifier of method of class or interface which is present in the package must be public
(This rule is optional in case of interface because interface methods by default public)
 Every package program should be save either with public class name or public Interface
name

Compile package programs


For compilation of package program first we save program with public className.java and it
compile using below syntax:

Syntax

N Nagarjuna OOP through Java


javac -d . className.java

Syntax
javac -d path className.java

Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a
separate folder for the given package in given path. When we give specific path then it create
a new folder at that location and when we use . (dot) then it crate a folder at current working
directory.

Note: Any package program can be compile but can not be execute or run. These program
can be executed through user defined program which are importing package program.

Example of package program


Package program which is save with A.java and compile by javac -d . A.java

Example
package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}

Import above class in below program using import packageName.className

Example
import mypack.A;
public class Hello
{
public static void main(String arg[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}

Explanations: In the above program first we create Package program which is save with
A.java and compiled by "javac -d . A.java". Again we import class "A" in class Hello using
"import mypack.A;" statement.

Difference between Inheritance and package

N Nagarjuna OOP through Java


Inheritance concept always used to reuse the feature within the program between class to
class, interface to interface and interface to class but not accessing the feature across the
program.
Package concept is to reuse the feature both within the program and across the programs
between class to class, interface to interface and interface to class.

Difference between package keyword and import keyword


Package keyword is always used for creating the undefined package and placing common
classes and interfaces.
import is a keyword which is used for referring or using the classes and interfaces of a
specific package.

N Nagarjuna OOP through Java


How to Create PACKAGE in Java: Learn with Example Program

What is Package in Java?


A Package is a collection of related classes. It helps organize your classes into a folder
structure and make it easy to locate and use them. More importantly, it helps improve re-
usability.

Each package in Java has its unique name and organizes its classes and interfaces into a
separate namespace, or name group.

Although interfaces and classes with the same name cannot appear in the same package, they
can appear in different packages. This is possible by assigning a separate namespace to each
package.

Syntax:-

package nameOfPackage;

steps of creating a package.

Let's study package with an example. We define a class and object and later compile this it in
our package p1. After compilation, we execute the code as a java package.

Step 1) Consider the following code,

Here,

N Nagarjuna OOP through Java


1. To put a class into a package, at the first line of code define package p1
2. Create a class c1
3. Defining a method m1 which prints a line.
4. Defining the main method
5. Creating an object of class c1
6. Calling method m1

Step 2) In next step, save this file as demo.java

Step 3) In this step, we compile the file.

N Nagarjuna OOP through Java


The compilation is completed. A class file c1 is created. However, no package is created?
Next step has the solution

Step 4) Now we have to create a package, use the command

javac –d . demo.java

This command forces the compiler to create a package.

The "." operator represents the current working directory.

Step 5) When you execute the code, it creates a package p1. When you open the java package
p1 inside you will see the c1.class file.

Step 6) Compile the same file using the following code

javac –d .. demo.java

N Nagarjuna OOP through Java


Here ".." indicates the parent directory. In our case file will be saved in parent directory
which is C Drive

File saved in parent directory when above code is executed.

Step 7) Now let's say you want to create a sub package p2 within our existing java package
p1. Then we will modify our code as

package p1.p2

Step 8) Compile the file

N Nagarjuna OOP through Java


As seen in below screenshot, it creates a sub-package p2 having class c1 inside the package.

Step 9) To execute the code mention the fully qualified name of the class i.e. the package
name followed by the sub-package name followed by the class name -

java p1.p2.c1

This is how the package is executed and gives the output as "m1 of c1" from the code file.

N Nagarjuna OOP through Java


Importing packages
To create an object of a class (bundled in a package), in your code, you have to use its fully
qualified name.

Example:

java.awt.event.actionListner object = new java.awt.event.actionListner();

But, it could become tedious to type the long dot-separated package path name for every class
you want to use. Instead, it is recommended you use the import statement.

Syntax

import packageName;

Once imported, you can use the class without mentioning its fully qualified name.

import java.awt.event.*; // * signifies all classes in this package are


imported
import javax.swing.JFrame // here only the JFrame class is imported
//Usage
JFrame f = new JFrame; // without fully qualified name.

Example: To import package

Step 1) Copy the code into an editor.

package p3;
import p1.*; //imports classes only in package p1 and NOT in the sub-
package p2
class c3{
public void m3(){
System.out.println("Method m3 of Class c3");
}
public static void main(String args[]){
c1 obj1 = new c1();
obj1.m1();
}
}

Step 2) Save the file as Demo2.java. Compile the file using the command javac –d .
Demo2.java

Step 3)Execute the code using the command java p3.c3

Packages - points to note:


 To avoid naming conflicts packages are given names of the domain name of the company in
reverse Ex: com.guru99. com.microsoft, com.infosys etc.

N Nagarjuna OOP through Java


 When a package name is not specified, a class is in the default package (the current working
directory) and the package itself is given no name. Hence you were able to execute
assignments earlier.
 While creating a package, care should be taken that the statement for creating package
must be written before any other import statements

// not allowed
import package p1.*;
package p3;

//correct syntax
package p3;
import package p1.*;

the java.lang package is imported by default for any class that you create in Java.

N Nagarjuna OOP through Java


Date : 30 August 2018

1. Write a Java program to demonstrate the ArithmeticException

int num1=10;
int num2=0;
int result=num1/num2;
System.out.println(result);

2. Write a Java program to demonstrate the NullPointerException

public static void display(String s){


System.out.println(s.length());
}

public static void main(String[] args) {


// TODO Auto-generated method stub
display(null);

String s =null;

System.out.println(s.charAt(0));

3. Write a Java program to demonstrate the IndexOutOfBoundsException

(i) ArrayIndexOutOfBoundsException

int arr[] ={1,2,3,4,5};


System.out.println(arr[7]);

(ii) StringIndexOutOfBoundsException

String s = "Hello";
System.out.println(s.charAt(8));

4. Write a Java program to demonstrate the IllegalArgumentException

import java.awt.Color;
public class IAE
{
public static void main(String args[])
{
Color clr1 = new Color(300, 150, 200);
}
}
ii)NumberFormatException
int num = Integer.parseInt("cvr");
System.out.println(num);
5. Write a Java program to demonstrate the ClassCastException

Object o = new Integer(10);

N Nagarjuna OOP through Java


String s=(String)o;

6. Write a Java program to demonstrate the StackOverflowError

7. Write a Java program to demonstrate the NoClassDefFoundError

class A
{

}
public class NoClassDefFoundErrorDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
A a = new A();
System.out.println(a);

8. Write a Java program to demonstrate the ClassNotFoundException

public class ClassNotFoundExceptionDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
try
{
Class.forName("Test");
}
catch(ClassNotFoundException e)
{
System.out.println("Sorry, class is not existing. " + e);
}

9. Write a Java program to demonstrate the NoSuchMethodException

class Data {

/* compile this without commenting first and later by commenting*/


/*public void foo() {
System.out.println("foo");
} */

}
public class NoSuchMethodErrorDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub

N Nagarjuna OOP through Java


Data d = new Data();
d.foo();

10.Write a Java program to demonstrate the NoSuchFieldException

class SomeClass
{
/* compile str variable without commenting first and later by
commenting*/
public static String str ="CVR College of Engineering";
}
public class NoSuchFieldErrorDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
System.out.println(SomeClass.str);

11.Write a Java program to demonstrate the IOException

12.Write a Java program to demonstrate the FileNotFoundException

13. For programs 1-12 , provide exception handling using try,catch

14. Write a Java program to demonstrate the usage of throws keyword

15.Write a Java program to demonstrate the usage of finally keyword.

N Nagarjuna OOP through Java


Unchecked Exception List
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NullPointerException
NumberFormatException
AssertionError
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError

Checked Exception List


Exception
IOException
FileNotFoundException
ParseException
CloneNotSupportedException
InterruptedException
ReflectiveOperationException

o ClassNotFoundException
o InstantiationException
o IllegalAccessException
o InvocationTargetException
o NoSuchFieldException
o NoSuchMethodException

Common checked exceptions defined in the java.lang package:

 ReflectiveOperationException
o ClassNotFoundException
o InstantiationException
o IllegalAccessException
o InvocationTargetException
o NoSuchFieldException
o NoSuchMethodException
 CloneNotSupportedException
 InterruptedException

Common checked exceptions defined in the java.io package:

 IOException

a.
o EOFException
o FileNotFoundException
o InterruptedIOException
o UnsupportedEncodingException

N Nagarjuna OOP through Java


o UTFDataFormatException
o ObjectStreamException

 InvalidClassException
 InvalidObjectException
 NotSerializableException
 StreamCorruptedException
 WriteAbortedException

Common Unchecked Exceptions in Java


Common unchecked exceptions in the java.lang package:

 ArithmeticException
 IndexOutOfBoundsException

a.
o ArrayIndexOutOfBoundsException
o StringIndexOutOfBoundsException

 ArrayStoreException
 ClassCastException
 EnumConstantNotPresentException
 IllegalArgumentException

a.
o IllegalThreadStateException
o NumberFormatException

 IllegalMonitorStateException
 IllegalStateException
 NegativeArraySizeException
 NullPointerException
 SecurityException
 TypeNotPresentException
 UnsupportedOperationException

ClassNotFoundException NoClassDefFoundError
It is an exception. It is of type
It is an error. It is of type java.lang.Error.
java.lang.Exception.
It occurs when an application tries to load a It occurs when java runtime system doesn’t
class at run time which is not updated in the find a class definition, which is present at
classpath. compile time, but missing at run time.
It is thrown by the application itself. It is
thrown by the methods like Class.forName(), It is thrown by the Java Runtime System.
loadClass() and findSystemClass().
It occurs when classpath is not updated with It occurs when required class definition is

N Nagarjuna OOP through Java


required JAR files. missing at runtime.

N Nagarjuna OOP through Java


Date : 23 August 2018

Getters&Setters, Abstract classes & Interfaces

Abstract class

1. Write a Person abstract class and then subclass that into Student and Faculty
classes. Use appropriate fields and methods and constructors.

2. Create an abstract class Shape with methods calc_area and calc_volume.


Derive three classes Sphere(radius) , Cone(radius, height) and Cylinder(radius,
height), Box(length, breadth, height) from it. Calculate area and volume of all.
(Use Method overriding).

Interfaces

1. Write a program to demonstrate the usage of interfaces.


2. Write a program which shows the concept of interface extension.
3. Use a program to show the advantages of inheriting from multiple
interfaces.

N Nagarjuna OOP through Java


Practice Questions

1) Getters and setters

GHMC has decided to organize a Fair at Hyderabad. The city Mayor(Bonthu


Rammoham) has announced a coding contest for creating the application for the
Fair. The Best application would be used for the fair and the developer gets a
cash prize. You are a well versed and aspiring Programmer in Hyderabad area.
Many programmers have enrolled themselves for the contest and you are one of
them.

A part of the Application requires a user prompt to create a new Item Type.
Hence create an ItemType class with the following private attributes.

Attributes Datatype
name String
deposit Double
costPerDay Double

Include appropriate Getters and Setters for the class.


The naming convention for Getters and Setters should be in Camel case.
For example, for the attribute name the getters and setters should be
getName() and setName().

Example :
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}

ItemType class contains the following methods.

Method
Description
Name
This method displays the details of the
void
ItemType as per specification provided in the
display()
sample input/output

Create a driver class called CodingContest. In the main method, obtain input
from the user in the console and create a new ItemType object and assign the

N Nagarjuna OOP through Java


values to the object's members using setters. Display the details by calling the
display method.

Display only one digit after the decimal point for Double datatype.

[Note: Strictly adhere to theObject Oriented Specifications given in the


problem statement.
All class names, attribute names and method names should be the same
as specified in the problem statement.]

[All text in bold corresponds to the input and rest corresponds to


output]
Sample Input/Output:

Enter the Item Type Name


Electronics
Enter the Deposit Amount
2500
Enter the Cost per day of the Item Type
125
Item Name:Electronics
Deposit Amount:2500.0
Cost Per Day:125.0

N Nagarjuna OOP through Java


1.Abstract Class - FundTransfer

Now we have implemented an abstract class in a simple program, we can


move on to a larger program. Let's try a larger application like fund
transfer before moving on to our application. So, in fund transfer there
are 3 types NEFT /IMPS/ RGTS . We can create an abstract class
FundTransfer. And extend it in the child classes. Create an abstract
method transfer and implement in all the child classes.

Create an abstract class FundTransfer with following attributes,

Attributes Datatype
accountNumber String
balance Double

and following methods,

Method Description
to check if the accountNumber is 10
Boolean
digits, transfer amount is non-negative
validate(Double
and less than balance, and return true,
transfer)
if not return false
Boolean
transfer(Double abstract method with no definition
transfer)

Create a class NEFTTransfer which extends FundTransfer and


implements transfer method,

Method Description
check if transfer amount+5% of transfer
Boolean amount is less than balance, then
transfer(Double subtracts transfer amount and 5%
transfer) service charge from balance and return
true, if not return false

Create a class IMPSTransfer which extends FundTransfer and


implements transfer method,

Method Description
Boolean check if transfer amount+2% of transfer
transfer(Double amount is less than balance, then

N Nagarjuna OOP through Java


transfer) subtracts transfer amount and 2%
service charge from balance and return
true, if not return false

Create a class RTGSTransfer which extends FundTransfer and


implements transfer method,

Method Description
check if transfer amount is greater than
Boolean
Rs.10000, then subtracts transfer
transfer(Double
amount from balance and return true, if
transfer)
not return false

Add appropriate getters/setters, constructors with super() to create


objects. Write a driver class Main to test them.

Note: Print "Account number or transfer amount seems to be wrong" if


validate function returns false. print "Transfer could not be made" if
transfer function returns false.
Print the statements in main method.

Refer sample input/output for other further details and format of the
output.

[All Texts in bold corresponds to the input and rest are


output]
Sample Input/Output 1:

Enter your account number:


1234567890
Enter the balance of the account:
10000
Enter the type of transfer to be made:
1.NEFT
2.IMPS
3.RTGS
1
Enter the amount to be transferred :
2000
Transfer occurred successfully
Remaining balance is 7900.0

Sample Input/Output 2:

Enter your account number:


1111111

N Nagarjuna OOP through Java


Enter the balance of the account:
10000
Enter the type of transfer to be made:
1.NEFT
2.IMPS
3.RTGS
2
Enter the amount to be transferred :
1000
Account number or transfer amount seems to be wrong

Sample Input/Output 3:

Enter your account number:


1234567890
Enter the balance of the account:
50000
Enter the type of transfer to be made:
1.NEFT
2.IMPS
3.RTGS
3
Enter the amount to be transferred :
7500
Transfer could not be made

2. Interface

The Interface defines a rule that any classes that implement it should
override all the methods. Let's implement Interface in our application.
We'll start simple, by including display method in the Stall interface. Now
all types of stalls that implement the interface should override the
method.

Create an interface Stall with the following method

Method Description
void display() Define the display method.

Create a class GoldStall which implements Stall interface with the


following private attributes

N Nagarjuna OOP through Java


Attributes Datatype
stallName String
cost Integer
ownerName String
tvSet Integer

Create default constructor and a parameterized constructor with


arguments in order GoldStall(String stallName, Integer cost, String
ownerName, Integer tvSet).
Include appropriate getters and setters.

Include following methods

Method Description
displays stall name, cost of the stall, owner
void
name and
display()
the numberoftv set.

Create a class PremiumStall which implements Stall interface with


following private attributes

Attributes Datatype
stallName String
cost Integer
ownerName String
projector Integer

Create default constructor and a parameterized constructor with


arguments in order PremiumStall(String stallName, Integer cost,
String ownerName, Integer projector).
Include appropriate getters and setters.

Include following methods

Method Description
displays stall name, cost of the stall, owner
void
name and
display()
number of projectors.

N Nagarjuna OOP through Java


Create a class ExecutiveStall which implements Stall interface
with following private attributes

Attributes Datatype
stallName String
cost Integer
ownerName String
screen Integer

Create default constructor and a parameterized constructor with


arguments in order ExecutiveStall(String stallName, Integer cost,
String ownerName, Integer screen).
Include appropriate getters and setters.

Include following methods

Method Description
displays stall name, cost of the stall, owner
void
name and
display()
number of screens.

Create a driver class named Main to test the above class.

Note:
Strictly adhere to the Object-Oriented Specifications given in the
problem statement.All class names, attribute names and method
names should be the same as specified in the problem statement.

Input Format:
The first input corresponds to choose the stall type.
The next line of input corresponds to the details of stall in CSV format
according to the stall type.

Output Format
The output consists of stall details.
Refer sample output for formatting specifications.

Sample Input/Output-1:
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
1
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner

N Nagarjuna OOP through Java


Name,Number of TV sets)
The Mechanic,120000,Johnson,10
Stall Name:The Mechanic
Cost:120000.Rs
Owner Name:Johnson
Number of TV sets:10

Sample Input/Output-2:
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
2
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner
Name,Number of Projectors)
Knitting plaza,300000,Zain,20
Stall Name:Knitting plaza
Cost:300000.Rs
Owner Name:Zain
Number of Projectors:20

Sample Input/Output-3:
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
3
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner
Name,Number of Screens)
Fruits Hunt,10000,Uber,7
Stall Name:Fruits Hunt
Cost:10000.Rs
Owner Name:Uber
Number of Screens:7

N Nagarjuna OOP through Java


Difference between Class and Interface
Class Interface

In class, you can instantiate variable In an interface, you can't instantiate


and create an object. variable and create an object.

Class can contain concrete(with The interface cannot contain


implementation) methods concrete(with implementation) methods

The access specifiers used with


In Interface only one specifier is
classes are private, protected and
used- Public.
public.

When to use Interface and Abstract Class?


 Use an abstract class when a template needs to be defined for a group of
subclasses
 Use an interface when a role needs to be defined for other classes,
regardless of the inheritance tree of these classes

Must know facts about Interface


 A Java class can implement multiple Java Interfaces. It is necessary that
the class must implement all the methods declared in the interfaces.
 Class should override all the abstract methods declared in the interface
 The interface allows sending a message to an object without concerning
which classes it belongs.
 Class needs to provide functionality for the methods declared in the
interface.
 All methods in an interface are implicitly public and abstract
 An interface cannot be instantiated
 An interface reference can point to objects of its implementing classes
 An interface can extend from one or many interfaces. Class can extend
only one class but implement any number of interfaces
 An interface cannot implement another Interface. It has to extend another
interface if needed.
 An interface which is declared inside another interface is referred as
nested interface
 At the time of declaration, interface variable must be initialized.
Otherwise, the compiler will throw an error.
 The class cannot implement two interfaces in java that have methods with
same name but different return type.

Summary:

N Nagarjuna OOP through Java


 The class which implements the interface needs to provide functionality
for the methods declared in the interface
 All methods in an interface are implicitly public and abstract
 An interface cannot be instantiated
 An interface reference can point to objects of its implementing classes
 An interface can extend from one or many interfaces. A class can extend
only one class but implement any number of interfaces

N Nagarjuna OOP through Java


Date : 16 August 2018

1. Write Java program to demonstrate

a)Single inheritance b) Multi Level inheritance c) Hierarchical inheritance

2. Write Java program to demonstrate

a) Super variable b) super() constructor c) super to invoke method

3. Write Java program to demonstrate

a) Method Overriding b) Dynamic Method Dispatch

4. Write Java program to demonstrate

Usage of final with a)method b) class

5. Write Java program to demonstrate Object class toString() method.

N Nagarjuna OOP through Java


Date : 9 August 2018 Methods,Passing parameters

1. Demonstrate method overloading concept

2. Write a Java program to pass object as parameter to method

3. Write a Java program that finds the minimum values in two different
arrays arrayOne and arrayTwo. i.e., find the minimum value in
arrayOne and arrayTwo . Use minArray() method to find the minimum
array element. Pass array variable as parameter to minArray() method.

4. Write a Java program to update array element using method


(updateArray()).Print the values of array before and after updation.

5. Write a Java program to perform subtraction of two matrices. Use


subArray() method to perform the operation. Check the array
dimensions/size in the beginning.

6. Write a Java program to find transpose of a matrix. Use


transposeArray() method.

N Nagarjuna OOP through Java


Parameter passing in Java

Objects communicate by calling methods on each other. A method call is used to invoke a
method on an object. Parameters in the method call provide one way of exchanging
information between the caller object and the callee object.

The syntax of a method call can be any one of the following:

<object reference>.<method name> (<actual parameter list>)

<class name>.<static method name> (<actual parameter list>)

<method name> (<actual parameter list>)

Let’s look at each element in method call syntax.

 object reference reference value denoting the object on which the method is called.
 method name name of the method to be called.
 class name name of the class, can be fully qualified name.
 static method name name of the static method to be called.
 actual parameter list are arguments that are sent to the called method.

 Parameter passing mechanism = agreement between the calling method and the
called method on how a parameter is passed between them
 The Java programming language uses only the pass-by-value mechanism.
 Agreement used in the Pass-by-value mechanism:

The calling method passes the information stored inside a variable by


passing (= copying) the value contained inside a variable into the parameter
variable.

Actual Parameter Vs Formal Parameter

Formal parameters are the parameters as they are known in the function/method definition.

Actual parameters are also known as arguments and are passed by the caller on method
invocation (calling the method).

N Nagarjuna OOP through Java


Date : 2 August 2018

Arrays, Scanner class

1. Write a Java program to print your name,college name, roll number, and
CGPA by reading the details from the user.(Use: Scanner class)

2. Write a Java Program to accept array elements and calculate its sum

3. Write a Java Program to perform addition of two matrices by reading


elements from the user.

4. Write a Java Program to perform matrix multiplication (accept the size(s)


from the user)

5. Write a program to find transpose of a square matrix of size N. Transpose


of a matrix is obtained by changing rows to columns and columns to rows.
Java Program to perform to find transpose of a matrix

Input:
The first line of input contains an integer T denoting the number of test cases.
Then T test cases follow. Each test case contains an integer n denoting the size
of the square matrix. Then in the next line are N*N space separated values of
the matrix.

Output:
For each test case output will be the space separated values of the transpose of
the matrix
Constraints:
1<=T<=1000
1<=N<=20

Example:
Input:
2
4
1111222233334444
2
1 2 -9 -2

Output:
1234123412341234
1 -9 2 -2

N Nagarjuna OOP through Java


Practice Questions

6. Write a program to input a list of integers in an array and arrange them in


a way similar to the to-and-fro movement of a Pendulum. The minimum
element out of the list of integers, must come in center position of array.
The number in the ascending order next to the minimum, goes to the left,
the next higher number goes to the right of minimum number and it
continues. As higher numbers are reached, one goes to either side of the
minimum value in a to-and-fro manner similar to that of a Pendulum.

Example:
INPUT – 1 2 3 4 5
OUTPUT – 5 3 1 2 4
INPUT – 11 12 31 14 5
OUTPUT – 31 12 5 11 14

7. Write a program to declare a square matrix A[ ][ ] of order „n‟. Allow the


user to input positive integers into this matrix. Perform the following tasks
on the matrix:

(i) Output the original matrix.

(ii) Find the SADDLE POINT for the matrix. If the matrix has no saddle
point, output the message “NO SADDLE POINT”.

[Note: A saddle point is an element of the matrix such that it is the


minimum element for the row to which it belongs and the maximum
element for the column to which it belongs. Saddle point for a given
matrix is always unique.]

Example: In the Matrix

456

789

513

Saddle point = 7 because it is the minimum element of row 2 and


maximum element of column 1

N Nagarjuna OOP through Java


8. Write a Program in Java to fill a square matrix of size „n*n” in a spiral
fashion (from the inside) with natural numbers from 1 to n*n, taking „n‟ as
input.

For example: if n = 5, then n*n = 25, hence the array will be filled as
given below.

9. Given a square matrix M [ ] [ ] of order „n‟. The maximum value possible


for „n‟ is 10. Accept three different characters from the keyboard and fill
the array according to the instruction given below.

 Fill the upper and lower elements formed by the intersection of the
diagonals by character 1.

 Fill the left and right elements formed by the intersection of the
diagonals by character 2.

 Fill both the diagonals by character 3.

Example 1

ENTER SIZE : 4

INPUT : FIRST CHARACTER : „*‟

SECOND CHARACTER : „?‟

THIRD CHARACTER : „#‟

OUTPUT :

#**#

?##?

?##?

N Nagarjuna OOP through Java


#**#

Example 2

ENTER SIZE : 5

INPUT : FIRST CHARACTER : „$‟

SECOND CHARACTER : „!‟

THIRD CHARACTER : „@‟

OUTPUT :

@$ $ $@

! @$@!

! !@ ! !

! @$@!

@$$ $@

Example 3

ENTER SIZE : 65

OUTPUT : SIZE OUT OF RANGE

N Nagarjuna OOP through Java


Scanner Class in Java
Scanner is a class in java.util package used for obtaining the input of the primitive types like
int, double etc. and strings.

It is the easiest way to read input in a Java program, though not very efficient if you want an
input method for scenarios where time is a constraint like in competitive programming.

 To create an object of Scanner class,

We usually pass the predefined object System.in, which represents the


standard input stream. We may pass an object of class File if we want to read input
from a file.

 To read numerical values of a certain data type XYZ,

the function to use is nextXYZ(). For example, to read a value of type short,
we can use nextShort()

 To read strings,

we use nextLine().

 To read a single character,


o we use next().charAt(0). next() function returns the next token/word in the
input as a string and charAt(0) function returns the first character in that string.

Commonly used methods of Scanner class

There is a list of commonly used Scanner class methods:

Method Description

public String next() it returns the next token from the scanner.

it moves the scanner position to the next line and returns the value as a
public String nextLine()
string.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

N Nagarjuna OOP through Java


public double
it scans the next token as a double value.
nextDouble()

N Nagarjuna OOP through Java


Date : 26 July 2018

1. Write a Java program to demonstrate constructor overloading

2. Write a Java program to demonstrate the usage of this keyword

In java, this is a reference variable that refers to the current object.

a. this --- to differentiate instance varaiable with local varaiable when


they have same name

b. this() --- to invoke current class constructor(constructor chanining)

c. this --- used to invoke current class method (implicitly).

3. Write a Java program to demonstrate the usage of static keyword

a. static variable

The static variable allocate memory only once in class area at the
time of class loading.

b. static method

c. static block

to initialize static variables, you can declare a static block that gets
executed exactly once, when the class is first loaded.

N Nagarjuna OOP through Java


Practice Questions

Question 1: Food Festival at CVR College


CVR College is planning to organize a Food Festival bringing together at one
place, a wide variety of cuisines from across the world on account of Christmas.
The Hotel Management has rented out a square hall of an indoor Auditorium for
this extravaganza. The side of the square hall is y inches in which a large square
table is placed for the display of the most popular and celebrated food items.
The side of the square table is x inches, such that x<y.

The Management wanted to fill the remaining floor area with a decorative carpet.
To get this done, they needed to know the floor area to be filled with the carpet.
Write a program to help the Management find the area of the region located
outside the square table, but inside the square hall.

Input Format:
First line of the input is an integer y, the side of the square hall.
Second line of the input is an integer x, the side of the square table placed for
display.

Output Format:
Output should display the area of the floor that is to be decorated with the
carpet.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and rest corresponds to output.]

Sample Input and Output 1:


Enter the side of the square hall
7
Enter the side of the square table placed for display
3
Area to be decorated is 40

Sample Input and Output 2:


Enter the side of the square hall
5
Enter the side of the square table placed for display
2
Area to be decorated is 21

N Nagarjuna OOP through Java


Question 2: Customized Welcome Message
Nandan Nilekani, the co-founder of “Infosys” company wished to design an Event
Management System that would let its Customers plan and host events seamlessly
via an online platform.

As a part of this requirement, Nandan Nilekani wanted to write a piece of code for his
company’s Infosys Event Management System that will display customized
welcome messages by taking Customers’ name as input. Help Nandan Nilekani on
the task.

Input Format:
First line of the input is a string that corresponds to a Customer’s name. Assume that
the maximum length of the string is 50.

Output Format:
Output should display the welcome message along with the Customer’s name.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and rest corresponds to output.]

Sample Input and Output:


Enter your name
Nagarjuna
Hello Nagarjuna ! Welcome to Infosys Event Management System

Question 3:
Wap to findout squareroot of a number without using any library function?

Question 4:
Write program to print the kth digit from last. e.g. input 23617 and k=4
output 3.

Question 5:
Write a Java program to find out Factorial of a number using

a. for loop
b. while loop
c. do while loop
d. switch,for loop,while loop and do while loop ?

N Nagarjuna OOP through Java


N Nagarjuna OOP through Java
Static keyword in java
The static keyword is used in java mainly for memory management. It is used with
variables, methods, blocks and nested class. It is a keyword that are used for share the same
variable or method of a given class. This is used for a constant variable or a method that is the
same for every instance of a class. The main method of a class is generally labeled static.

No object needs to be created to use static variable or call static methods, just put the class
name before the static variable or method to use them. Static method can not call non-static
method.

In java language static keyword can be used for following

 variable (also known as class variable)


 method (also known as class method)
 block
 nested class

Static variable
If any variable we declared as static is known as static variable.

 Static variable is used for fulfill the common requirement. For Example company name of
employees,college name of students etc. Name of the college is common for all students.
 The static variable allocate memory only once in class area at the time of class loading.

Advantage of static variable


Using static variable we make our program memory efficient (i.e it saves memory).

When and why we use static variable


Suppose we want to store record of all employee of any company, in this case employee id is
unique for every employee but company name is common for all. When we create a static
variable as a company name then only once memory is allocated otherwise it allocate a
memory space each time for every employee.

Syntax for declare static variable:


public static variableName;

Syntax for declare static method:


public static void methodName()
{
.......
.......
}

N Nagarjuna OOP through Java


Syntax for access static methods and static variable

Syntax
className.variableName=10;
className.methodName();

Example
public static final double PI=3.1415;
public static void main(String args[])
{
......
......
}

Difference between static and final keyword


static keyword always fixed the memory that means that will be located only once in the
program where as final keyword always fixed the value that means it makes variable values
constant.

Note: As for as real time statement there concern every final variable should be declared the
static but there is no compulsion that every static variable declared as final.

Example of static variable.

In the below example College_Name is always same, and it is declared as static.

Static Keyword Example in Java


class Student
{
int roll_no;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.name);
System.out.println(Student.College_Name);
Student s2=new Student();
s2.roll_no=200;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.name);
System.out.println(Student.College_Name);

N Nagarjuna OOP through Java


}
}

Example
Output:
100
abcd
ITM
200
zyx
ITM

In the above example College_Name variable is commonly sharable by both S1 and S2


objects.

In the above image static data variable are store in method area and non static variable is
store in java stack.

Why Main Method Declared Static ?


Because object is not required to call static method if main() is non-static method, then jvm
create object first then call main() method due to that face the problem of extra memory
allocation.

N Nagarjuna OOP through Java


Difference between Static and non-static method in Java
In case of non-static method memory is allocated multiple time whenever method is calling.
But memory for static method is allocated only once at the time of class loading. Method of a
class can be declared in two different ways

 Non-static methods
 Static methods

Difference between non-static and static Method


Non-Static method Static method

These method never be preceded by static


These method always preceded by static keyword
keyword
Example:
Example:
1 static void fun2()
void fun1() {
{ ......
...... ......
...... }
}
Memory is allocated multiple time whenever Memory is allocated only once at the time of class
2
method is calling. loading.

It is specific to an object so that these are These are common to every object so that it is also
3
also known as instance method. known as member method or class method.

These methods always access with object


These property always access with class reference
reference
4 Syntax:
Syntax:

className.methodname();
Objref.methodname();
If any method wants to be execute multiple If any method wants to be execute only once in the
5
time that can be declare as non static. program that can be declare as static .

Note: In some cases static methods not only can access with class reference but also can
access with object reference.

Example of Static and non-Static Method

Example
class A
{
void fun1()
{
System.out.println("Hello I am Non-Static");

N Nagarjuna OOP through Java


}
static void fun2()
{
System.out.println("Hello I am Static");
}
}
class Person
{
public static void main(String args[])
{
A oa=new A();
oa.fun1(); // non static method
A.fun2(); // static method
}
}

Output
Hello I am Non-Static
Hello I am Static

Following table represent how the static and non-static properties are accessed in the different
static or non-static method of same class or other class.

Program to accessing static and non-static properties.


Example
class A
{
int y;
void f2()
{
System.out.println("Hello f2()");
}
}
class B

N Nagarjuna OOP through Java


{
int z;
void f3()
{
System.out.println("Hello f3()");
A a1=new A();
a1.f2();
}
}
class Sdemo
{
static int x;
static void f1()
{
System.out.println("Hello f1()");
}
public static void main(String[] args)
{
x=10;
System.out.println("x="+x);
f1();
System.out.println("Hello main");
B b1=new B();
b1.f3();
}
}

N Nagarjuna OOP through Java


Date : 19 July 2018

1. Write a Java program to demonstrate Arithmetic operators


Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.

Java Arithmetic Operators


Operator Meaning
+ Addition (also used for string concatenation)
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Remainder Operator

2. Write a Java program to demonstrate Unary operators


Unary Operators
Unary operator performs operation on only one operand.

Operator Meaning
+ Unary plus (not necessary to use since numbers are positive without using it)
- Unary minus; inverts the sign of an expression
++ Increment operator; increments value by 1
-- decrement operator; decrements value by 1
! Logical complement operator; inverts the value of a boolean

3. Write a Java program to demonstrate Relational operators


Equality and Relational Operators
The equality and relational operators determines the relationship between two
operands. It checks if an operand is greater than, less than, equal to, not equal to and
so on. Depending on the relationship, it results to either true or false.

Java Equality and Relational Operators


Operator Description Example
== equal to 5 == 3 is evaluated to false
!= not equal to 5 != 3 is evaluated to true
> greater than 5 > 3 is evaluated to true

N Nagarjuna OOP through Java


Java Equality and Relational Operators
Operator Description Example
< less than 5 < 3 is evaluated to false
>= greater than or equal to 5 >= 5 is evaluated to true
<= less then or equal to 5 <= 5 is evaluated to true

4. Write a Java program to demonstrate logical operators(short-


circuit)
Logical Operators
The logical operators || (conditional-OR) and && (conditional-AND) operates on
boolean expressions. Here's how they work.

Java Logical Operators


Operator Description Example
conditional-OR; true if either of the boolean false || true is evaluated
||
expression is true to true
conditional-AND; true if all boolean false && true is evaluated
&&
expressions are true to false

5. Write a Java program to demonstrate ternary operator

Ternary Operator
The conditional operator or ternary operator ?: is shorthand for if-then-else
statement. The syntax of conditional operator is:

variable = Expression ? expression1 : expression2

Here's how it works.

 If the Expression is true, expression1 is assigned to variable.


 If the Expression is false, expression2 is assigned to variable.

6. Write a Java program to demonstrate Bitwise and Bit shift


operators
Bitwise and Bit Shift Operators
To perform bitwise and bit shift operators in Java, these operators are used.

Java Bitwise and Bit Shift Operators


Operator Description
~ Bitwise Complement
<< Left Shift

N Nagarjuna OOP through Java


Java Bitwise and Bit Shift Operators
Operator Description
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

7. Write a Java program to add one to a given number. The use of


operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc are not allowed.

N Nagarjuna OOP through Java


Java Bitwise and Bit Shift Operators

Java provides 4 bitwise and 3 bit shift operators to perform bit operations.

Java Bitwise and Bit Shift Operators

Operator Description

| Bitwise OR

& Bitwise AND

~ Bitwise Complement

^ Bitwise XOR

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

Bitwise and bit shift operators are used on integral types (byte, short, int and
long) to perform bit-level operations.

Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.

The | operator compares corresponding bits of two operands. If either of the bits
is 1, it gives 1. If not, it gives 0. For example,

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

Example 1: Bitwise OR

N Nagarjuna OOP through Java


class BitwiseOR {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

result = number1 | number2;


System.out.println(result);
}
}

When you run the program, the output will be:

29

Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.

The & operator compares corresponding bits of two operands. If both bits are 1,
it gives 1. If either of the bits is not 1, it gives 0. For example,

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Example 2: Bitwise AND


class BitwiseAND {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

result = number1 & number2;


System.out.println(result);
}
}

When you run the program, the output will be:

Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is
denoted by ~.

N Nagarjuna OOP through Java


The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.

35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Example 3: Bitwise Complement


class Complement {
public static void main(String[] args) {

int number = 35, result;

result = ~number;
System.out.println(result);
}
}

When you run the program, the output will be:

-36

Why are we getting output -36 instead of 220?

It's because the compiler is showing 2's complement of that number; negative notation of the
binary number.

For any integer n, 2's complement of n will be -(n+1).

Decimal Binary 2's complement


--------- --------- ---------------------------------------
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)

Note: Overflow is ignored while computing 2's complement.

The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence,
the output is -36 instead of 220.

Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.

The ^ operator compares corresponding bits of two operands. If corresponding bits are
different, it gives 1. If corresponding bits are same, it gives 0. For example,

N Nagarjuna OOP through Java


12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
| 00011001
________
00010101 = 21 (In decimal)

Example 4: Bitwise XOR


class Xor {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

result = number1 ^ number2;


System.out.println(result);
}
}

When you run the program, the output will be:

21

Signed Left Shift


The left shift operator << shifts a bit pattern to the left by certain number of specified bits,
and zero bits are shifted into the low-order positions.

212 (In binary: 11010100)

212 << 1 evaluates to 424 (In binary: 110101000)


212 << 0 evaluates to 212 (In binary: 11010100)
212 << 4 evaluates to 3392 (In binary: 110101000000)

Example 5: Signed Left Shift


class LeftShift {
public static void main(String[] args) {

int number = 212, result;

System.out.println(number << 1);


System.out.println(number << 0);
System.out.println(number << 4);
}
}

When you run the program, the output will be:

424

N Nagarjuna OOP through Java


212
3392

Signed Right Shift


The right shift operator >> shifts a bit pattern to the right by certain number of specified bits.

212 (In binary: 11010100)

212 >> 1 evaluates to 106 (In binary: 01101010)


212 >> 0 evaluates to 212 (In binary: 11010100)
212 >> 8 evaluates to 0 (In binary: 00000000)

If the number is a 2's complement signed number, the sign bit is shifted into the high-order
positions.

Example 6: Signed Right Shift


class RightShift {
public static void main(String[] args) {

int number = 212, result;

System.out.println(number >> 1);


System.out.println(number >> 0);
System.out.println(number >> 8);
}
}

When you run the program, the output will be:

106
212
0

Unsigned Right Shift


The unsigned right shift operator << shifts zero into the leftmost position.

Example 7: Signed and UnSigned Right Shift


class RightShift {
public static void main(String[] args) {

int number1 = 5, number2 = -5;

// Signed right shift

N Nagarjuna OOP through Java


System.out.println(number1 >> 1);

// Unsigned right shift


System.out.println(number1 >>> 1);

// Signed right shift


System.out.println(number2 >> 1);

// Unsigned right shift


System.out.println(number2 >>> 1);
}
}

When you run the program, the output will be:

2
2
-3
2147483645

Notice, how signed and unsigned right shift works differently for 2's complement.

The 2's complement of 2147483645 is 3.

N Nagarjuna OOP through Java

You might also like