Core Java Paper - Part III Solution
Core Java Paper - Part III Solution
Q.1. What are the most important features of OOP languages? Differentiate between class and instance variables.
- Important Features of OOP Languages:-
Class variables v/s instance variables - While methods represent the behavior of an object, variables represent the state
of an object. Variables may be of two types – Class variables and Instance Variables. Class variables are common to all
instances of that class where-as instance variables are specific to an object.
1) Class variables, also called as static variables, are declared with the keyword static.
1 class StaticVariables
2 {
3 static int i; //Static Variable
4
5 static String s; //Static Variable
6 }
2) Class variables are common to all instances of that class i.e. these variables will be shared by all objects of that class.
Hence, changes made to these variables through one object will reflect in all objects.
class ClassVariables
{
static int i = 10; //Static Variable
static String s = "STATIC"; //Static Variable
}
public class MainClass
{
public static void main(String[] args)
{
ClassVariables obj1 = new ClassVariables();
ClassVariables obj2 = new ClassVariables();
//accessing class variables through obj1
[Link](obj1.i); //Output : 10
[Link](obj1.s); //Output : STATIC
//accessing class variables through obj2
[Link](obj2.i); //Output : 10
[Link](obj2.s); //Output : STATIC
//Making changes to class variables through obj2
obj2.i = 20;
obj2.s = "STATIC - STATIC";
//accessing class variables through obj1
[Link](obj1.i); //Output : 20
[Link](obj1.s); //Output : STATIC - STATIC
//accessing class variables through obj2
[Link](obj2.i); //Output : 20
[Link](obj2.s); //Output : STATIC - STATIC
}
}
3) Class variables can be referred through class name as well as object reference.
class A
{
static int i = 100; //Class Variable
}
public class MainClass
{
public static void main(String[] args)
{
//Referring class variable through class name
[Link](A.i);
A a = new A();
//Referring class variable through object reference
[Link](a.i);
}
}
Instance Variables In Java :
1) Instance variables, also called as non-static variables are declared without static keyword.
class InstanceVariables
{
int i; //Instance Variable
2) Instance variables are not common to all instances of a class. Each object will maintain its own copy of instance variables. Henc
made to instance variables through one object will not reflect in another object.
class InstanceVariables
{
int i = 10; //Instance Variable
String s = "NON-STATIC"; //Instance Variable
}
public class MainClass
{
public static void main(String[] args)
{
InstanceVariables obj1 = new InstanceVariables();
InstanceVariables obj2 = new InstanceVariables();
//obj1 instance variables
[Link](obj1.i); //Output : 10
[Link](obj1.s); //Output : NON-STATIC
//obj2 instance variables
[Link](obj2.i); //Output : 10
[Link](obj2.s); //Output : NON-STATIC
//changing obj1 instance variables
obj1.i = 20;
obj1.s = "INSTANCE VARIABLE";
//obj1 instance variables
[Link](obj1.i); //Output : 20
[Link](obj1.s); //Output : INSTANCE VARIABLE
//obj2 instance variables
[Link](obj2.i); //Output : 10
[Link](obj2.s); //Output : NON-STATIC
}
}
class A
{
int i = 100; //Instance Variable
}
public class MainClass
{
public static void main(String[] args)
{
A a = new A();
//Referring instance variable through object reference
[Link](a.i);
//You can't refer instance variable through class name, you will get compile time error
//[Link](A.i);
}
}
What the differences are between structured and object oriented programming? [Explain the features of
JAVA.*(Explained above)]
- Java String -
In java, string is basically an object that represents sequence of char values. An array of characters works same as java
string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(), substring() etc.
CharSequence Interface
The CharSequence interface is used to represent sequence of characters. It is implemented by String, StringBuffer and
StringBuilder classes. It means, we can create string in java by using these 3 classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. For
mutable string, you can use StringBuffer and StringBuilder classes.
We will discuss about immutable string later. Let's first understand what is string in java and how to create the string
object.
Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The
[Link] class is used to create string object.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool,
a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object with the value
"Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
2) By new keyword
java
strings
example
The [Link] class provides many useful methods to perform operations on sequence of char values.
No Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns formatted string
4 static String format(Locale l, String format, Object... returns formatted string with given locale
args)
5 String substring(int beginIndex) returns substring for given begin index
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end
index
7 boolean contains(CharSequence s) returns true or false after matching the sequence
of char value
8 static String join(CharSequence delimiter, returns a joined string
CharSequence... elements)
9 static String join(CharSequence delimiter, Iterable<? returns a joined string
extends CharSequence> elements)
10 boolean equals(Object another) checks the equality of string with object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatenates specified string
13 String replace(char old, char new) replaces all occurrences of specified char value
14 String replace(CharSequence old, CharSequence replaces all occurrences of specified
new) CharSequence
15 static String equalsIgnoreCase(String another) Compares another string. It doesn't check case.
16 String[] split(String regex) returns splitted string matching regex
17 String[] split(String regex, int limit) returns splitted string matching regex and limit
18 String intern() returns interned string
19 int indexOf(int ch) returns specified char value index
20 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
21 int indexOf(String substring) returns specified substring index
22 int indexOf(String substring, int fromIndex) returns specified substring index starting with
given index
23 String toLowerCase() returns string in lowercase.
24 String toLowerCase(Locale l) returns string in lowercase using specified locale.
25 String toUpperCase() returns string in uppercase.
26 String toUpperCase(Locale l) returns string in uppercase using specified locale.
27 String trim() removes beginning and ending spaces of this
string.
28 static String valueOf(int value) converts given type into string. It is overloaded.
OR
What is inheritance? Explain its different types. Write a java program to implement multiple inheritance.
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields
also.
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of
"extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and the new class is called child or
subclass.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
Output :-
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code
reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple inheritance is supported through interface only. We will learn about interfaces later.
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. [Link]();
11. [Link]();
12. }}
Output :-
barking...
eating...
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){[Link]("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. [Link]();
14. [Link]();
15. [Link]();
16. }}
Output:
weeping...
barking...
eating...
File: [Link]
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){[Link]("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. [Link]();
14. [Link]();
15. //[Link]();//[Link]
16. }}
Output:
meowing...
eating..
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same
method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error now.
1. class A{
2. void msg(){[Link]("Hello");}
3. }
4. class B{
5. void msg(){[Link]("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. [Link]();//Now which msg() method would be invoked?
12. }
13. }
When Run the program :- Compile Time Error
// Program to illustrate Interface :-
interface i
{
public void display();
}
class a implements i
{
public void display()
{
[Link]("This is Interface");
}
}
class inter_face
{
public static void main(String args[])
{
a a1=new a();
[Link]();
}
}
A general interface between Java and the native system, used for windowing, events, and layout managers. This API
is at the core of Java GUI programming and is also used by Swing and Java 2D. It contains:
The interface between the native windowing system and the Java application;
The core of the GUI event subsystem;
Several layout managers;
The interface to input devices such as mouse and keyboard; and
A [Link] package for use with the Clipboard and Drag and Drop.
A basic set of GUI widgets such as buttons, text boxes, and menus. It also provides the AWT Native Interface, which
enables rendering libraries compiled to native code to draw directly to an AWT Canvas object drawing surface.
AWT also makes some higher level functionality available to applications, such as:
AWT hierarchy
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The
classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for
creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button,
textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like button,
textfield etc.
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default
false.
Why AWT is platform dependent? Java AWT calls native platform (Operating systems) subroutine for creating
components such as textbox, checkbox, button etc. For example an AWT GUI having a button would have a different
look and feel across platforms like windows, Mac OS & Unix, this is because these platforms have different look and feel
for their native buttons and AWT directly calls their native subroutine that creates the button. In simple, an application
build on AWT would look like a windows application when it runs on Windows, but the same application would look like
a Mac application when runs on Mac OS.
AWT is rarely used now days because of its platform dependent and heavy-weight nature. AWT components are
considered heavy weight because they are being generated by underlying operating system (OS). For example if you are
instantiating a text box in AWT that means you are actually asking OS to create a text box for you.
All the elements like buttons, text fields, scrollbars etc are known as components. In AWT we have classes for each
component as shown in the above diagram. To have everything placed on a screen to a particular position, we have to
add them to a container. A container is like a screen wherein we are placing components like buttons, text fields,
checkbox etc. In short a container contains and controls the layout of components. A container itself is a component
(shown in the above hierarchy diagram) thus we can add a container inside container.
Types of containers:
As explained above, a container is a place wherein we add components like text field, button, checkbox etc. There are
four types of containers available in AWT: Window, Frame, Dialog and Panel. As shown in the hierarchy diagram above,
Frame and Dialog are subclasses of Window class.
AWT Example
1. import [Link].*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. [Link](30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
- Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are following classes that represents the layout managers:
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link] etc.
1. Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region
(area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five
constants for each region:
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between
the components.
1. import [Link].*;
2. import [Link].*;
3. public class Border {
4. JFrame f;
5. Border(){
6. f=new JFrame();
7.
8. JButton b1=new JButton("NORTH");;
9. JButton b2=new JButton("SOUTH");;
10. JButton b3=new JButton("EAST");;
11. JButton b4=new JButton("WEST");;
12. JButton b5=new JButton("CENTER");;
13.
14. [Link](b1,[Link]);
15. [Link](b2,[Link]);
16. [Link](b3,[Link]);
17. [Link](b4,[Link]);
18. [Link](b5,[Link]);
19.
20. [Link](300,300);
21. [Link](true);
22. }
23. public static void main(String[] args) {
24. new Border();
25. }
26. }
2. Java GridLayout -
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between
the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns
alongwith given horizontal and vertical gaps.
1. import [Link].*;
2. import [Link].*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. [Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);
20. [Link](b6);[Link](b7);[Link](b8);[Link](b9);
21.
22. [Link](new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. [Link](300,300);
26. [Link](true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. }
31. }
3. Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of
applet or panel.
1. import [Link].*;
2. import [Link].*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. [Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);
16.
17. [Link](new FlowLayout([Link]));
18. //setting flow layout of right alignment
19.
20. [Link](300,300);
21. [Link](true);
22. }
23. public static void main(String[] args) {
24. new MyFlowLayout();
25. } }
4. Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides
four constants. They are as follows:
Note: BoxLayout class is found in [Link] package.
1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.
1. import [Link].*;
2. import [Link].*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample1 b=new BoxLayoutExample1();
22. }
23. }
Example of BoxLayout class with X-AXIS
1. import [Link].*;
2. import [Link].*;
3.
4. public class BoxLayoutExample2 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample2() {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample2 b=new BoxLayoutExample2();
22. }
23. }
5. Java CardLayout
The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats
each component as a card that is why it is known as CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the given name.
Example of CardLayout class
1. import [Link].*;
2. import [Link].*;
3.
4. import [Link].*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space
15. [Link](card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. [Link](this);
21. [Link](this);
22. [Link](this);
23.
24. [Link]("a",b1);[Link]("b",b2);[Link]("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. [Link](c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
33. [Link](400,400);
34. [Link](true);
35. [Link](EXIT_ON_CLOSE);
36. }
37. }
Q.4. Explain how to set font of an applet using Font class. Give Suitable code segment to demonstrate.
- A font represents a particular size and style of text. The same character will appear different in different fonts. In Java,
a font is characterized by a font name, a style, and a size. The available font names are system dependent, but you can
always use the following four strings as font names: "Serif", "SansSerif", "Monospaced", and "Dialog". In the original Java
1.0, the font names were "TimesRoman", "Helvetica", and "Courier". You can still use the older names if you want. (A
"serif" is a little decoration on a character, such as a short horizontal line at the bottom of the letter i. "SansSerif" means
"without serifs." "Monospaced" means that all the characters in the font have the same width. The "Dialog" font is the
one that is typically used in dialog boxes.)
The style of a font is specified using named constants that are defined in the Font class. You can specify the style as one
of the four values:
[Link],
[Link],
[Link], or
[Link] + [Link].
The size of a font is an integer. Size typically ranges from about 10 to 36, although larger sizes can also be used. The size
of a font is usually about equal to the height of the largest characters in the font, in pixels, but this is not a definite rule.
The size of the default font is 12.
Java uses the class named [Link] for representing fonts. You can construct a new font by specifying its font
name, style, and size in a constructor:
Every graphics context has a current font, which is used for drawing text. You can change the current font with
the setFont() method. For example, if g is a graphics context and bigBoldFont is a font, then the
command [Link](bigBoldFont) will set the current font of g to bigBoldFont. You can find out the current font of g by
calling the method [Link](), which returns an object of type Font.
Every component has an associated font. It can be set with the instance method setFont(font), which is defined in
theComponent class. When a graphics context is created for drawing on a component, the graphic context's current font
is set equal to the font of the component.
import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link];
}
}
OR
What is Multithreaded programming? Explain how threads are created in java. Explain the need of thread
synchronization, with suitable example.
- Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts
that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of
execution. Thus, multithreading is a specialized form of multitasking. You are almost certainly acquainted with
multitasking, because it is supported by virtually all modern operating systems. However, there are two distinct types of
multitasking: process-based and thread-based. It is important to understand the difference between the two.
For most readers, process-based multitasking is the more familiar form. A process is, in essence, a program that is
executing. Thus, process-based multitasking is the feature that allows your computer to run two or more programs
concurrently. For example, process-based multitasking enables you to run the Java compiler at the same time that you
are using a text editor. In process-based multitasking, a program is the smallest unit of code that can be dispatched by
the scheduler.
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a
single program can perform two or more tasks simultaneously. For instance, a text editor can format text at the same
time that it is printing, as long as these two actions are being performed by two separate threads. Thus, process-based
multitasking deals with the "big picture," and thread-based multitasking handles the details.
Multitasking threads require less overhead than multitasking processes. Processes are heavyweight tasks that require
their own separate address spaces. Inter process communication is expensive and limited. Context switching from one
process to another is also costly. Threads, on the other hand, are lightweight. They share the same address space and
cooperatively share the same heavyweight process. Inter thread communication is inexpensive, and context switching
from one thread to the next is low cost. While Java programs make use of process-based multitasking environments,
process-based multitasking is not under the control of Java. However, multithreaded
multitasking is.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can
be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates,
because idle time is common. For example, the transmission rate of data over a network is much slower than the rate at
which the computer can process it. Even local file system resources are read and written at a much slower pace than
they can be processed by the CPU. And, of course, user input is much slower than the computer. In a traditional, single-
threaded environment, your program has to wait for each of these tasks to finish before it can proceed to the next
one—even though the CPU is sitting idle most of the time.
Multithreading lets you gain access to this idle time and put it to good use.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
When we start two or more threads within a program, there may be a situation when multiple threads try to access the
same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple
threads try to write within a same file then they may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the
resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated
with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources within this block. Following is the general form of the
synchronized statement −
Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized
statement represents. Now we are going to see two examples, where we will print a counter using two different
threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print
counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads.
Example
class PrintDemo {
try {
} catch (Exception e) {
[Link]("Thread interrupted.");
private Thread t;
PrintDemo PD;
threadName = name;
PD = pd;
synchronized(PD) {
[Link]();
if (t == null) {
[Link] ();
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch ( Exception e) {
[Link]("Interrupted");
This produces the same result every time you run this program −
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Q.5. Explain Datagram. Explain the classes for implementing it.
- Definition :- A datagram is an independent, self-contained message sent over the network whose arrival, arrival time,
and content are not guaranteed.
The DatagramPacket and DatagramSocket classes in the [Link] package implement system-
independent datagram communication using UDP.
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order.
Additionally, packet delivery is not guaranteed.
1. //[Link]
2. import [Link].*;
3. public class DSender{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket();
6. String str = "Welcome java";
7. InetAddress ip = [Link]("[Link]");
8.
9. DatagramPacket dp = new DatagramPacket([Link](), [Link](), ip, 3000);
10. [Link](dp);
11. [Link]();
12. }
13. }
1. //[Link]
2. import [Link].*;
3. public class DReceiver{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket(3000);
6. byte[] buf = new byte[1024];
7. DatagramPacket dp = new DatagramPacket(buf, 1024);
8. [Link](dp);
9. String str = new String([Link](), 0, [Link]());
10. [Link](str);
11. [Link]();
12. }
13. }
OR
What is TCP/IP socket? Explain basic networking features of java.
- Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits,
listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which
the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and
port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection.
This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same
local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue
to listen to the original socket for connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to
communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Definition:
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a
port number so that the TCP layer can identify the application that data is destined to be sent to.
An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two
endpoints. That way you can have multiple connections between your host and the server.
The [Link] package in the Java platform provides a class, Socket, that implements one side of a two-way connection
between your Java program and another program on the network. The Socket class sits on top of a platform-dependent
implementation, hiding the details of any particular system from your Java program. By using the [Link] class
instead of relying on native code, your Java programs can communicate over the network in a platform-independent fashion.
Additionally, [Link] includes the ServerSocket class, which implements a socket that servers can use to listen for and
accept connections to clients. This lesson shows you how to use the Socket and ServerSocket classes.
If you are trying to connect to the Web, the URL class and related classes (URLConnection, URLEncoder) are probably
more appropriate than the socket classes. In fact, URLs are a relatively high-level connection to the Web and use sockets as
part of the underlying implementation. See Working with URLs for information about connecting to the Web via URLs.
The term network programming refers to writing programs that execute across multiple devices (computers), in which
the devices are all connected to each other using a network.
The [Link] package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level
communication details, allowing you to write programs that focus on solving the problem at hand.
The [Link] package provides support for the two common network protocols −
TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication between two
applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be
transmitted between applications.
This chapter gives a good understanding on the following two subjects −
Socket Programming − This is the most widely used concept in Networking and it has been explained in very
detail.
URL Processing − This would be covered separately. Click here to learn about URL Processing in Java language.
Socket Programming
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket
on its end of the communication and attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the communication. The client and the
server can now communicate by writing to and reading from the socket.
The [Link] class represents a socket, and the [Link] class provides a mechanism for the server
program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets −
The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to
the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number
to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and the port number.
If communication is established, the client now has a Socket object capable of communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the server that is connected to
the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an
OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's
InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams at the same time. Following are
the useful classes providing complete set of methods to implement sockets.
ServerSocket Class Methods
The [Link] class is used by server applications to obtain a port and listen for client requests.
The ServerSocket class has four constructors −
[Link]. Method & Description
public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.
3
Connects to the specified host and port, creating a socket on the local host at the
specified address and port.
public Socket()
5 Creates an unconnected socket. Use the connect() method to connect this socket to a
server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect
to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and the server have a Socket
object, so these methods can be invoked by both the client and the server.
[Link]. Method & Description
4 String getHostAddress()
Returns the IP address string in textual presentation.
String getHostName()
5
Gets the host name for this IP address.
String toString()
7
Converts this IP address to a String.
import [Link].*;
import [Link].*;
try {
[Link]();
} catch (IOException e) {
[Link]();
}
Socket Server Example
The following GreetingServer program is an example of a server application that uses the Socket class to listen for
clients on a port number specified by a command-line argument −
Example
import [Link].*;
import [Link].*;
[Link](10000);
while(true) {
try {
[Link]() + "...");
[Link]([Link]());
+ "\nGoodbye!");
[Link]();
} catch (SocketTimeoutException s) {
break;
} catch (IOException e) {
[Link]();
break;
try {
[Link]();
} catch (IOException e) {
[Link]();
}
Compile the client and the server and then start the server as follows −
$ java GreetingServer 6066
Waiting for client on port 6066...
Check the client program as follows −
Output
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/[Link]:6066
Server says Thank you for connecting to /[Link]:6066
Goodbye!