0% found this document useful (0 votes)
6 views44 pages

Core Java Paper - Part III Solution

The document discusses key concepts of Object-Oriented Programming (OOP) in Java, focusing on class and instance variables, their characteristics, and differences. It explains string handling in Java, including the immutability of strings and various methods provided by the String class. Additionally, it covers inheritance in Java, its types, and provides examples of single, multilevel, and hierarchical inheritance, while noting that multiple inheritance is not supported through classes.

Uploaded by

Jhonson
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)
6 views44 pages

Core Java Paper - Part III Solution

The document discusses key concepts of Object-Oriented Programming (OOP) in Java, focusing on class and instance variables, their characteristics, and differences. It explains string handling in Java, including the immutability of strings and various methods provided by the String class. Additionally, it covers inheritance in Java, its types, and provides examples of single, multilevel, and hierarchical inheritance, while noting that multiple inheritance is not supported through classes.

Uploaded by

Jhonson
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

[BCA-PART-III ]

Core Java Paper - 2017


PART – III

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.

Class Variables In Java :

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

String s; //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
}
}

3) Instance variables can be referred only through object reference.

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

Class Variables Instance Variables


Class variables are declared with keyword static. Instance variables are declared without static keyword.
Instance variables are not shared between the objects of a
Class variables are common to all instances of a class. class. Each instance will have their own copy of instance
These variables are shared between the objects of a class. variables.
As class variables are common to all objects of a class, As each object will have its own copy of instance variables,
changes made to these variables through one object will changes made to these variables through one object will
reflect in another. not reflect in another object.
Class variables can be accessed using either class name or Instance variables can be accessed only through object
object reference. reference.
OR

What the differences are between structured and object oriented programming? [Explain the features of
JAVA.*(Explained above)]

Structured Programming Object Oriented Programming


Structured Programming is focuses on process/ logical Object Oriented Programming is focuses on data.
structure and then data required for that process.
Structured programming follows top-down approach. Object oriented programming follows bottom-up
approach.
Structured Programming is also known as Modular Object Oriented Programming supports inheritance,
Programming and a subset of procedural programming encapsulation, abstraction, polymorphism, etc.
language.
In Structured Programming, Programs are divided into In Object Oriented Programming, Programs are divided
small self-contained functions. into small entities called objects.
Structured Programming is less secure as there is no way Object Oriented Programming is more secure as having
of data hiding. data hiding feature.
Structured Programming can solve moderately complex Object Oriented Programming can solve any complex
programs. programs.
Structured Programming provides less reusability, more Object Oriented Programming provides more reusability,
function dependency. less function dependency.
Less abstraction and less flexibility. More abstraction and more flexibility.
Q.1. What do you mean by string handling? Explain various methods of string handling.

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

The [Link] class implements Serializable, Comparable and CharSequence interfaces.

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.

How to create String object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

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.

Why java uses concept of string literal?

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

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable


In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Java String Example

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating java string by new keyword
7. [Link](s1);
8. [Link](s2);
9. [Link](s3);
10. }}
Test it Now

java
strings
example

Java String class methods -

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.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.
Syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

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.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is


the superclass. Relationship between two classes is Programmer IS-A
[Link] means that Programmer is a type of Employee.

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.

Types of inheritance in java

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.

Note: Multiple inheritance is not supported in java through class.

Single Inheritance Example

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

Multilevel Inheritance Example

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

Hierarchical Inheritance Example

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

Why multiple inheritance is not supported in java?

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

Output :- This is Interface


Q.3. What is AWT? Explain AWT in brief.
- Abstract Window Toolkit (AWT) is a set of application program interfaces ( API s) used by Java programmers to create
graphical user interface ( GUI ) objects, such as buttons, scroll bars, and windows. AWT is part of the Java Foundation
Classes ( JFC ) from Sun Microsystems, the company that originated Java. The JFC are a comprehensive set of
GUI class libraries that make it easier to develop the user interface part of an application program.
The AWT provides two levels of APIs:

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:

Access to the system tray on supporting systems; and


The ability to launch some desktop applications such as web browsers and email clients from a Java application.
Neither AWT nor Swing are inherently thread safe. Therefore, code that updates the GUI or processes events should
execute on the Event dispatching thread. Failure to do so may result in a deadlock or race condition. To address this
problem, a utility class called SwingWorker allows applications to perform time-consuming tasks following user-
interaction events in the event dispatching thread.
As the AWT is a bridge to the underlying native user-interface, its implementation on a new operating system may
involve a lot of work, especially if it involves any of the AWT GUI widgets, because each of them requires that its native
peers be developed from scratch.

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.

Useful Methods of Component class

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.

Components and containers

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.

Window: An instance of the Window class has no border and no title


Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without an associated instance of
the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for holding components. An
instance of the Panel class provides a container to which to add components.
Frame: A frame has title, border and menu bars. It can contain several components like buttons, text fields, scrollbars
etc. This is most widely used container while developing an application in AWT.

Java AWT Example

We can create a GUI using Frame in two ways:


1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.

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

8. setLayout(null);//no layout manager


9. setVisible(true);//now frame will be visible, by default
not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}
OR

What are the different types of layout managers? Explain.

- 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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

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.

Example of BorderLayout class:

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.

Constructors of GridLayout class

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.

Example of GridLayout class

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.

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical
gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.

Example of FlowLayout class

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.

Fields of BoxLayout class

1. public static final int X_AXIS


2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.

Example of BoxLayout class with Y-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.

Constructors of CardLayout class

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.

Commonly used methods of CardLayout class

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:

Font plainFont = new Font("Serif", [Link], 12);


Font bigBoldFont = new Font("SansSerif", [Link], 24);

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.

Example Given Below :-

import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link];

public class Applet6 extends Applet {


public void paint(Graphics g) {
Font mycustomefont = new Font(“Arial”, [Link],20);
[Link](mycustomefont);
[Link](“This is Sample Text using Arial Font and Bold”, 10, 50);

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

There are two ways to create threads in java :-

1) by extending Thread class :-

2) by implementing runnable interface :-

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().

1. public void run(): is used to perform action for a thread.


Starting a thread:

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.

1) Java Thread Example by extending Thread class

// WAP in java to illustrate Multi_threading :- [By extending thread Class]


class a extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
[Link](+i);
}
}
}
class th_1
{
public static void main(String args[])
{
a a1=new a();
[Link]();
}
}
Output: 1234

2) Java Thread Example by implementing Runnable interface

// WAP in java to illustrate Multi-threading: - [By Using Runnable Interface]


class a implements Runnable
{
public void run()
{
for(int i=1;i<5;i++)
{
[Link](+i);
}
}
}
class th_2
{
public static void main(String args[])
{
a a1=new a();
Thread m=new Thread(a1);
[Link]();
}
}
Output: 1234
Thread Synchronization: -

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.

The synchronization is mainly used to:-

1. To prevent thread interference.


2. To prevent consistency problem.

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.

Multithreading Example with Synchronization


Here is the same example which prints counter value in sequence and every time we run it, it produces the same result.

Example

class PrintDemo {

public void printCount() {

try {

for(int i = 5; i > 0; i--) {

[Link]("Counter --- " + i );


}

} catch (Exception e) {

[Link]("Thread interrupted.");

class ThreadDemo extends Thread {

private Thread t;

private String threadName;

PrintDemo PD;

ThreadDemo( String name, PrintDemo pd) {

threadName = name;

PD = pd;

public void run() {

synchronized(PD) {

[Link]();

[Link]("Thread " + threadName + " exiting.");

public void start () {

[Link]("Starting " + threadName );

if (t == null) {

t = new Thread (this, threadName);

[Link] ();

public class TestThread {


public static void main(String args[]) {

PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );

ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

[Link]();

[Link]();

// wait for threads to end

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 :-

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.

Commonly used Constructors of DatagramSocket class


o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port
Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port
Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it
with the specified port number and host address.

Java DatagramPacket class :-

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.

Commonly used Constructors of DatagramPacket class


o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the
packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This
constructor is used to send the packets.

Example of Sending DatagramPacket by DatagramSocket :-

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

Example of Receiving DatagramPacket by DatagramSocket :-

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 ServerSocket(int port) throws IOException


1 Attempts to create a server socket bound to the specified port. An exception occurs if
the port is already bound by another application.

public ServerSocket(int port, int backlog) throws IOException


2 Similar to the previous constructor, the backlog parameter specifies how many incoming
clients to store in a wait queue.

public ServerSocket(int port, int backlog, InetAddress address) throws IOException


Similar to the previous constructor, the InetAddress parameter specifies the local IP
3 address to bind to. The InetAddress is used for servers that may have multiple IP
addresses, allowing the server to specify which of its IP addresses to accept client
requests on.
public ServerSocket() throws IOException
4 Creates an unbound server socket. When using this constructor, use the bind() method
when you are ready to bind the server socket.
If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to
the specified port and is ready for client requests.
Following are some of the common methods of the ServerSocket class −
[Link]. Method & Description

public int getLocalPort()


1 Returns the port that the server socket is listening on. This method is useful if you
passed in 0 as the port number in a constructor and let the server find a port for you.

public Socket accept() throws IOException


Waits for an incoming client. This method blocks until either a client connects to the
2 server on the specified port or the socket times out, assuming that the time-out value
has been set using the setSoTimeout() method. Otherwise, this method blocks
indefinitely.

public void setSoTimeout(int timeout)


3 Sets the time-out value for how long the server socket waits for a client during the
accept().

public void bind(SocketAddress host, int backlog)


4 Binds the socket to the specified server and port in the SocketAddress object. Use this
method if you have instantiated the ServerSocket using the no-argument constructor.
When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does
connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A
TCP connection now exists between the client and the server, and communication can begin.
Socket Class Methods
The [Link] class represents the socket that both the client and the server use to communicate with each
other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the
return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server −
[Link]. Method & Description

public Socket(String host, int port) throws UnknownHostException, IOException.


This method attempts to connect to the specified server at the specified port. If this
1
constructor does not throw an exception, the connection is successful and the client is
connected to the server.

public Socket(InetAddress host, int port) throws IOException


2 This method is identical to the previous constructor, except that the host is denoted by
an InetAddress object.

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(InetAddress host, int port, InetAddress localAddress, int localPort)


4 throws IOException.
This method is identical to the previous constructor, except that the host is denoted by
an InetAddress object instead of a String.

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

public void connect(SocketAddress host, int timeout) throws IOException


1 This method connects the socket to the specified host. This method is needed only
when you instantiate the Socket using the no-argument constructor.

public InetAddress getInetAddress()


2
This method returns the address of the other computer that this socket is connected to.

public int getPort()


3
Returns the port the socket is bound to on the remote machine.

public int getLocalPort()


4
Returns the port the socket is bound to on the local machine.

public SocketAddress getRemoteSocketAddress()


5
Returns the address of the remote socket.

public InputStream getInputStream() throws IOException


6 Returns the input stream of the socket. The input stream is connected to the output
stream of the remote socket.

public OutputStream getOutputStream() throws IOException


7 Returns the output stream of the socket. The output stream is connected to the input
stream of the remote socket.

public void close() throws IOException


8 Closes the socket, which makes this Socket object no longer capable of connecting again
to any server.

InetAddress Class Methods


This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would need while
doing socket programming −
[Link]. Method & Description

static InetAddress getByAddress(byte[] addr)


1
Returns an InetAddress object given the raw IP address.

static InetAddress getByAddress(String host, byte[] addr)


2
Creates an InetAddress based on the provided host name and IP address.

static InetAddress getByName(String host)


3
Determines the IP address of a host, given the host's name.

4 String getHostAddress()
Returns the IP address string in textual presentation.

String getHostName()
5
Gets the host name for this IP address.

static InetAddress InetAddress getLocalHost()


6
Returns the local host.

String toString()
7
Converts this IP address to a String.

Socket Client Example


The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and
then waits for a response.
Example

// File Name [Link]

import [Link].*;

import [Link].*;

public class GreetingClient {

public static void main(String [] args) {

String serverName = args[0];

int port = [Link](args[1]);

try {

[Link]("Connecting to " + serverName + " on port " + port);

Socket client = new Socket(serverName, port);

[Link]("Just connected to " + [Link]());

OutputStream outToServer = [Link]();

DataOutputStream out = new DataOutputStream(outToServer);

[Link]("Hello from " + [Link]());

InputStream inFromServer = [Link]();

DataInputStream in = new DataInputStream(inFromServer);


[Link]("Server says " + [Link]());

[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

// File Name [Link]

import [Link].*;

import [Link].*;

public class GreetingServer extends Thread {

private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException {

serverSocket = new ServerSocket(port);

[Link](10000);

public void run() {

while(true) {

try {

[Link]("Waiting for client on port " +

[Link]() + "...");

Socket server = [Link]();

[Link]("Just connected to " + [Link]());


DataInputStream in = new DataInputStream([Link]());

[Link]([Link]());

DataOutputStream out = new DataOutputStream([Link]());

[Link]("Thank you for connecting to " + [Link]()

+ "\nGoodbye!");

[Link]();

} catch (SocketTimeoutException s) {

[Link]("Socket timed out!");

break;

} catch (IOException e) {

[Link]();

break;

public static void main(String [] args) {

int port = [Link](args[0]);

try {

Thread t = new GreetingServer(port);

[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!

You might also like