Java Tasks 25 10 2018
Java Tasks 25 10 2018
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. 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
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,
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.
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:
}
public static void main(String [] args)
{
MenuDemo obj = new MenuDemo();
}
E:\Java\AWT\Nagarjuna>javac MenuDemo.java
E:\Java\AWT\Nagarjuna>java MenuDemo
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
/**
* @deprecated
* reason for why it was deprecated
*/
@Deprecated
public void showDeprecatedMessage(){
System.out.println("This method is marked as deprecated");
}
@Deprecated
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.
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.
Example:
Message.java
A java class on which threads will work and call wait and notify methods.
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{
@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
@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.
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.
Consumer
1. Check if Buffer has items. If empty, then wait() for buffer to get filled.
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;
}
public Buffer()
{
this.empty = true;
}
/*Consumer */
class Consumer extends Thread {
private Buffer 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;
}
}
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.
@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.
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:
@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
}
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();
}
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.
5. Write a Java program to check whether two String objects contain the
same data.
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"
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
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
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:
Sample Input/output 2:
Problem Requirements:
Java
Keyword Min Count Max Count
trim 1 -
contains 1 -
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:
Problem Requirements:
Java
Keyword Min Count Max Count
StringBuilder 1 -
substring 1 -
replace 1 -
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.
= 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";
= ;
String Concatenation:
Concatenation is joining of two or more strings.
Check the below code snippet,and it explains the two methods to perform string
concatenation.
Let’s ask the Java String class a few questions and see if it can answer them ;)
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.
output:
Length of String: 8
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.
Output:
Character at position 5: t
Index of character 'S': 4
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.
Output:
Character at position 5: t
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.
Output:
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.
Output:
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.
Output:
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.
Output:
Just use the “toLowercase()” or “ToUpperCase()” methods against the Strings that need to be
converted.
Output:
String h1 = "hello";
h1 = "hello"+"world";
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
System.out.println(S1);
System.out.println(S1);
Name
StringBuffer
Synopsis
Class Name:
java.lang.StringBuffer
Superclass:
java.lang.Object
Immediate Subclasses:
None
Interfaces Implemented:
java.io.Serializable
Availability:
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
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:
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();
Constructors
StringBuffer
public StringBuffer()
Description
Creates a StringBuffer object that does not contain any characters and has a
capacity of 16 characters.
capacity
Throws
NegativeArraySizeException
If capacity is negative.
Description
Creates a StringBuffer object that does not contain any characters and has the
specified capacity.
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
A boolean value.
Returns
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.
A char value.
Returns
Description
This method appends the given character to the end of the sequence of characters
stored in this StringBuffer object.
str
Returns
Description
This method appends the characters in the given array to the end of the sequence of
characters stored in this StringBuffer object.
str
offset
len
Returns
Throws
StringIndexOutOfBoundsException
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.
A double value.
Returns
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.
Returns
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.
An int value.
Returns
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.
A long value.
Returns
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.
A reference to an object.
Returns
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.
str
A String object.
Returns
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
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
index
Returns
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
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.
getChars
public synchronized void getChars(int srcBegin, int srcEnd, char dst[],
int dstBegin)
Parameters
srcBegin
srcEnd
dst
dstBegin
Throws
StringIndexOutOfBoundsException
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
offset
A boolean value.
Returns
Throws
StringIndexOutOfBoundsException
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.
offset
A char value.
Returns
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.
offset
str
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.
offset
A double value.
Returns
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.
offset
A float value.
Returns
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.
offset
An int value.
Returns
Throws
StringIndexOutOfBoundsException
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.
offset
A long value.
Returns
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.
offset
obj
Returns
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.
offset
str
A String object.
Returns
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
length
public int length()
Returns
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
Description
This method reverses the sequence of characters stored in this StringBuffer object.
setCharAt
public synchronized void setCharAt(int index, char ch)
Parameters
index
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
setLength
public synchronized void setLength(int newLength)
Parameters
newLength
Throws
StringIndexOutOfBoundsException
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
Packages
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.
Example
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
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;
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
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.
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.
Type of package
Package are classified into two type which are given below.
Syntax
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
package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}
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.
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;
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.
Here,
javac –d . demo.java
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.
javac –d .. demo.java
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 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.
Example:
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.
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
// 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.
int num1=10;
int num2=0;
int result=num1/num2;
System.out.println(result);
String s =null;
System.out.println(s.charAt(0));
(i) ArrayIndexOutOfBoundsException
(ii) StringIndexOutOfBoundsException
String s = "Hello";
System.out.println(s.charAt(8));
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
class A
{
}
public class NoClassDefFoundErrorDemo {
class Data {
}
public class NoSuchMethodErrorDemo {
class SomeClass
{
/* compile str variable without commenting first and later by
commenting*/
public static String str ="CVR College of Engineering";
}
public class NoSuchFieldErrorDemo {
o ClassNotFoundException
o InstantiationException
o IllegalAccessException
o InvocationTargetException
o NoSuchFieldException
o NoSuchMethodException
ReflectiveOperationException
o ClassNotFoundException
o InstantiationException
o IllegalAccessException
o InvocationTargetException
o NoSuchFieldException
o NoSuchMethodException
CloneNotSupportedException
InterruptedException
IOException
a.
o EOFException
o FileNotFoundException
o InterruptedIOException
o UnsupportedEncodingException
InvalidClassException
InvalidObjectException
NotSerializableException
StreamCorruptedException
WriteAbortedException
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
Abstract class
1. Write a Person abstract class and then subclass that into Student and Faculty
classes. Use appropriate fields and methods and constructors.
Interfaces
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
Example :
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
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
Display only one digit after the decimal point for Double datatype.
Attributes Datatype
accountNumber String
balance Double
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)
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
Method Description
Boolean check if transfer amount+2% of transfer
transfer(Double amount is less than balance, then
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
Refer sample input/output for other further details and format of the
output.
Sample Input/Output 2:
Sample Input/Output 3:
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.
Method Description
void display() Define the display method.
Method Description
displays stall name, cost of the stall, owner
void
name and
display()
the numberoftv set.
Attributes Datatype
stallName String
cost Integer
ownerName String
projector Integer
Method Description
displays stall name, cost of the stall, owner
void
name and
display()
number of projectors.
Attributes Datatype
stallName String
cost Integer
ownerName String
screen Integer
Method Description
displays stall name, cost of the stall, owner
void
name and
display()
number of screens.
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
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
Summary:
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.
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.
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:
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).
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
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
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
(ii) Find the SADDLE POINT for the matrix. If the matrix has no saddle
point, output the message “NO SADDLE POINT”.
456
789
513
For example: if n = 5, then n*n = 25, hence the array will be filled as
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.
Example 1
ENTER SIZE : 4
OUTPUT :
#**#
?##?
?##?
Example 2
ENTER SIZE : 5
OUTPUT :
@$ $ $@
! @$@!
! !@ ! !
! @$@!
@$$ $@
Example 3
ENTER SIZE : 65
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.
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().
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.
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.
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.]
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.]
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 ?
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.
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.
Syntax
className.variableName=10;
className.methodName();
Example
public static final double PI=3.1415;
public static void main(String args[])
{
......
......
}
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
Output:
100
abcd
ITM
200
zyx
ITM
In the above image static data variable are store in method area and non static variable is
store in java stack.
Non-static methods
Static methods
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.
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
class A
{
void fun1()
{
System.out.println("Hello I am Non-Static");
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.
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
Ternary Operator
The conditional operator or ternary operator ?: is shorthand for if-then-else
statement. The syntax of conditional operator is:
Java provides 4 bitwise and 3 bit shift operators to perform bit operations.
Operator Description
| Bitwise OR
~ Bitwise Complement
^ Bitwise XOR
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,
Example 1: Bitwise OR
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,
Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is
denoted by ~.
result = ~number;
System.out.println(result);
}
}
-36
It's because the compiler is showing 2's complement of that number; negative notation of the
binary number.
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,
21
424
If the number is a 2's complement signed number, the sign bit is shifted into the high-order
positions.
106
212
0
2
2
-3
2147483645
Notice, how signed and unsigned right shift works differently for 2's complement.