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

Single Line Comments

This document contains questions and answers related to Java programming and GUI development. It discusses topics like object oriented programming languages, platform independence in Java, the Java compilation process, comments in Java programs, syntax errors, RAD programming using NetBeans IDE, Java data types, operators, selection statements, loops, and event handling in GUI programming.

Uploaded by

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

Single Line Comments

This document contains questions and answers related to Java programming and GUI development. It discusses topics like object oriented programming languages, platform independence in Java, the Java compilation process, comments in Java programs, syntax errors, RAD programming using NetBeans IDE, Java data types, operators, selection statements, loops, and event handling in GUI programming.

Uploaded by

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

Q1. Name any two Object Oriented Programming languages?

Ans. C++ and Java

Q2. Why is java called a platform independent language?

Ans Java program can be easily moved from one computer system to another, anywhere
anytime.

Changes and upgrade in operating system, processors and system resources will not force any
change in the Java program. Hence it is called a platform independent language.

Q3. Elaborate the java Compilation process.

Ans. The source program is first converted into a byte code using a java compiler. This byte
code is machine independent i.e. same for all the machines. Later the byte code is executed
on the machine using an interpreter.

Q4. Why do we write a comment in a program? What are the two ways of writing comment
in a java Program?

Ans. Comments are added to a program for the following purposes:-

1. Make the more readable and understandable

2. For future references we can add comments in a Java program in the following ways:

i) Adding // before the line which is to be commented. This can be used only for single

line comments.

ii) using a pair of /* and */ for multi-line comments.

Q5. What is a syntax error in context of a program? Give an example.

Ans. Error in the way of writing a statement in a program, results in a syntax error.

For e.g.

for ( i=0, i<=100. i++), will result in a syntax because the program has written

comma instead of a semi colon in the for loop.

Q6. What is RAD programming? Why is program development in java using Netbeans IDE
is

RAD?

Ans. RAD stands for Rapid Application Development. A programming style which aims at
building programs fastly through the use of tools and wizards is called RAD.
Program development using Netbeans IDE is RAD as it

• provides GUI

• Provides online help and suggestions during typing of the program

(using ctrl+ Spacebar key)

• Error alerts while typing of the program.

Q7. What is IDE? Name two IDE for Programming in java.

Ans. A programming environment, where all the tools required for programming are
available under one roof is called IDE. Two IDE for Java are Netbeans and BlueJ

Q8. Name any two type of Tokens available in Java.

Ans. Keyword, Identifier, Literal, Punctuators ad Operators.

Q9. What are primitive data types? Name the various primitive data type available in Java.

Ans. Data types that are directly available with java are called primitive data type.

Various primitive data types available in java are byte, short, int, long, float,

double, char and boolean.

Q10. What are Reference data types?

Ans. Data types created by the programmer using the primitive data type are called

reference data type e.g. Classes, interfaces etc.

Q11. What is type casting?

Ans. Converting a value form one type to another is called type casting.

For e.g. int a = 5 . here ‘a’ is a integer, which can be cased to float as follows

float b = (float) a;

Q12. Name and explain the usage of any two data types used in Java to store numbers with
decimals.

Ans. Two data types available in java for storing numbers with decimals are

1. float: for single precision floating point values for e.g. float num = 10.0F

2. double: for double precision floating point value. This is the default data type
for decimal numbers. for e.g. double num = 10.0

Q13. What are Keywords? Give two examples of keywords available in Java.

Ans. Keywords are words that have a specific predefined meaning in Java. They cannot be
used as variable names. Eg. void, private, if, while etc.

Q14. Name and explain the usage of any one relational and one logical operator in Java.

Ans. One relational operator in java is ==. This operator results in true if both its operands
are equal otherwise false. One logical operator in java is &&. This operator is used to
combine two logical values. The result of the && will be true if and only if both its operands
are true otherwise false.

Q15. What is the difference between = and == operator in java?

Ans. Represent an assignment operator. It sets the value of the variable on its left side with
the result of expression on its right side. == represent a conditional equal to operator. It
checks for the equality of both its operands. If both the operands are equal, condition
evaluates to true otherwise to false.

Q16. Name the two type of selection statement available in Java.

Ans. Two selection statement available in java are ‘if’ and ‘Switch’

Q17. Write the purpose of Switch Statement with the help of an example. Which Java
Statement can be used in place of switch statement? In the switch statement, what happens if
every case fails and there is no default option?

Ans. A Switch statement is used execute a statement from a group of statement based on the
result of a expression. The expression must result in either of byte, short, integer or character.
An ‘if statement’ can be used in place of switch statement. In a switch statement if none of
the statement satisfies and even there is no default case then nothing would happen. This
would not result in any sort of error.

Q18. What is the purpose of ‘break’ statement in java?

Ans. Break is used to terminate the current switch statement or the loop.

Q19. What is the purpose of ‘continue’ statement in java?

Ans. Continue statement skips the remaining part of the current loop and begins the next
iteration of the loop.

Q20 Find the output of the following code snippet written in java

public static void main(String []args)

{
long a=78345,s1=0,s2=0,r;

while(a>0)

r=a%10;

if (r%4==0)

s1+= r;

else

s2+=r;

a/=10;

System.out.println("S1 ="+ s1);

System.out.println("S2 ="+ s2);

Ans. Output:

s1= 12

s2= 15

Q21. Correct the errors in the following program segment written in JAVA. You are just
required to write the corrected code, underlying the corrections made.

public Static Void Main (String [] args)

Integer Nos = 100;

while (Nos => 45)

If (Nos % 5 = 0);

Nos+=10;
otherwise

Nos + = 20;

Ans: Corrected Code


public static void main (String [] args)

int Nos = 100;

while (Nos >= 45)

if (Nos % 5 == 0)_

Nos+=10;

else

Nos + = 20;

Unsolved Questions
1. What will be output of the following code:

byte b;

double d= 417.35;

b= (byte) d;

system.out.println(b);

2. Given the value of a variable, write a statement, without using if construct, which will
produce the absolute value of a variable.
3. What is wrong with the following code fragment?

Switch (x)

case 1:

n1= 10;

n2= 20;

case 2:

n3=30;

break;

n4= 40;

4. What will be the output of the following program code?

int m = 100;

int n = 300;

while(++m < --n);

System.out.println(m+” “+ n);

5. What does the following fragment display

String s = “Six:” + 3+ 3;

System.out.println(s);

6. What is the output of the following code?

String s = new string();

System.out.println(“s = “ + s);

7. What will be the output of the following code snippet?

int x= 10;

int y = 20;
if ((x<y)||(x=5) > 10)

System.out.println(x);

else

System.out.println(y);

8. State the output of the following program:

public static void main(String args[ ])

int x = 10;

int y = 15;

System.ou.println((x>y)? 3.14: 3);

9. State the output of the following program:

public static void main(String args[ ])

int x = 10;

float y = 10.0;

System.ou.println((x>y)? true: false);

10. Given a pacakage named EDU.student, how would you import a class named Test
contained in this package? Write one line statement.

11. Consider the following class definition:

Class Student

abstract double result( )

}
This code will not compile since a keyword is missing in the first line. What is the

keyword?

CHAPTER-4

SOLVED QUESTIONS

1.What does getPassword() on a password field return?

(a) a string (b) an integer (c) a character array.

Ans: (c) a character array

2. Which of the following component is the best suited to accept the country of the user?

A. List B. Combo box C. Radio button D. Check box

Ans: B. Combo box

3. What command do you need to write in actionPerformed() event handler of a button, in


order to make it exit button?

a. System.out.println(); b. System.exit(0); c. System.out.print()

Ans: b. System.exit(0);

4.What method would you use, in order to simulate a button’s(namely Okbtn) click event,
without any mouse activity from user’s side?

a. Okbtn.setText() b.Okbtn.getText() c. Okbtn.doClick()

Ans: Okbtn.doClick()

5. What would be the name of the event handler method in the ListSelection listener interface
for a list namely CheckList to handle its item selections?

a. CheckListValueChanged() b. getSelectedValue() c. clearSelection()

Ans: a. CheckListValueChanged()

6. Which control displays text that the user cannot directly change or edit?

a.TextField b. Checkbox c. Combobox d. Label

Ans: d.Label

7.Which control provides basic text editing facility?


a.TextField b. Checkbox c. Combobox d. Label

Ans: a. TexfField

8. Occurrence of an activity is called:

a. Function b. Class c. Object d. Event

Ans: d.Event.

9. Which property is used to set the text of the Label?

a. font b.text c.name d. icon

Ans: b.text

10. The object containing the data to be exhibited by the combo box by which property.

a. editable b. model c.selectedIndex d.selectedItem

Ans: b. model

11. What is GUI programming?

Ans: A GUI(Graphical User Interface) is an interface that uses pictures and other graphic
entities along with text, to interact with user.

12. How is swing related to GUI programming?

Ans: We can create a GUI application on Java platform using Swing API (Application
Programming Interface), which is part of Java Foundation Classes(JFC).

15. What property would you set to assign access key to a button?

Ans: mnemonic property is used to assign access key or shortcut (Alt + Key).

16. Which method can programmatically performs the click action of a push button?

Ans: private void TestBtnActionPerfomed(java.awt.action.ActionEvent evt){ }.

17. Which property would you set for setting the password character as ‘$’?

Ans:echoChar

18. Which method returns the password entered in a password field?

Ans: char [] getPassword().

19. Which list property do you set for specifying the items for the list.
Ans: model

20. Which method would you use to determine the index of selected item in a list?

Ans: int getSelectedIndex().

21. Which method would you use to insert an item at specified index, in the list?

Ans: void setSelectedIndex( int index).

22. How you can determine whether 5th item in a list is selected or not?

Ans: isSelectedIndex(4).

23. Which method you would use to insert ‘Hello’ at 10th position in the Text Area control.

Ans:void insert(“Hello”, 9).

24. Which method you would like to use to insert an Icon (picture) on a Push Button.

Ans: void setIcon(Icon).

25. Which property would you like to set to make a Combo box editable?

Ans: editable.

27. Name three commonly used properties and methods of the following controls.

(a) text field (b) text area (c) Check Box

Ans: (a) Properties: text, font, editable. Methods: void setText(), String getText(), void

setEditable(boolean).

(b) Properties: enabled, editable, wrapStyleWord Methods: setText(), getText(), isEditable()

(c) Properties:font, text, selected . Methods: getText(), isEnabled(), isSelected().

29. What is the difference between-

(a) Text field & Text area

(b) Text field & password field

(c) Radio Button & Check Box

Ans: (a) A text field’s text property can hold single line of text unless it is an HTML text.
While a text area’s text can hold any number of lines of text depending upon its rows
property.
(b) Though a text field and a password field can obtain a single line of text from the user, yet
these are different. A password field displays the obtained text in encrypted form on screen
while text field displays the obtained text in unencrypted form.

(c) Radio Button: A jRadioButton control belongs to JRadioButton class of Swing controls.
It is used to get choices from the user. It is grouped control, so that only one can be selected
at a time among them. Radio Button works in group, so that they must be kept in a
ButtonGroup container control like so that only one can be selected at the same time.

Some features of jRadioButton control are-

_ It can be used to input choices typed input to the application.

_ Only one Radio button can be selected at a time.

_ They must be kept in a Button Group container control to form a group.

Check box: A jCheckBox control belongs to JCheckBox class of Swing controls. It indicates
whether a particular condition is on or off. You can use Check boxes to give users true/false
or yes/no options. Check Boxes may works independently to each other, so that any number
of check boxes can be selected at the same time.

Some features of jCheckBox control are-

_ It can be used to input True/False or Yes/No typed input to the application.

_ Multiple check boxes can be selected at the same time.

30. What is the significance of following properties of a text area ?

(a) lineWrap (b) wrapStyleword

Ans: (a) Defines Wrapping featureenable/disable (b) Determines where line wrapping occurs.
If true, the component attempts to wrap only at word boundaries. This property is ignored
unless linewrap is set to true.

31. What is the significance of a button group? How do you create a button group?

Ans: We must add a ButtonGroup control to the frame to group the check boxes by using
Button

Group property of the check box. By dragging buttongroup control from palette window.

32. What do you understand by focus?

Ans: A Focus is the ability to receive user input/response through Mouse or Keyboard. When
object or control has focus, it can receive input from user.

ı An object or control can receive focus only if its enabled and visible property are set to true.
ı Most of the controls provides FOCUS_GAINED() and FOCUS_LOST() method in
FocusEvent by the FocusListener. FOCUS_LOST() is generally used for validation of data.

ı You can give focus to an object at run time by invoking the requestFocus() method in the
code.

Ex. jTextBox2.requestFocus();

33. What is meant by scope of a variable?

Ans: In Java, a variable can be declared any where in the program but before using them.

ı The area of program within which a variable is accessible, known as its scope.

ı A variable can be accessed within the block where it is declared.

int x=10;

if (a>b)

{ int y=5;

………… Scope of x and y

else

{ int z=3;

……. Scope of z

……….

34. Create a Java Desktop Application to find the incentive (%) of Sales for a Sales Person on
the basis of following feedbacks:

Feedback Incentive (%)

Maximum Sales

Excellent Customer Feedback


Maximum Count Customer

10

Note: that the sales entry should not be space.Calculate the total incentive as :Sales amount*
Incentive. The feedback will be implemented in JCheckBox controls.Using a JButton’s
(Compute Incentive) click event handler,display the total incentives in a JTextField control.
Assume the nomenclature of the swing components of your own.

Note that the JFrame from IDE window will be shown as given:

Ans:- private void btnIncActionPerformed (java.awt.ActionEvent evt) {

int sales = 0;

if (! txtSales.getText( ).trim( ).equals( “”)){

sales-Integer.parseInt(txtSales.getText( ).trim ( ));

double incentive = 0.0;

if (jCheckBox1.isSelected ( )) {

incentive = incentive + 0.1;

if (jCheckBox2.isSelected ( )) {

incentive = incentive + 0.8;

if (jCheckBox3.isSelected ( )) {

incentive = incentive + 0.05;

txtInc.setText ( “ “ + Math.round(sales * incentive));

}
35. Assume the following interface built using Netbeans used for bill calculation of a ice-
cream parlor. The parlor offers three verities of ice-cream – vanilla, strawberry, chocolate.
Vanilla icecream costs Rs. 30, Strawberry Rs. 35 and Chocolate Rs. 50. A customer can
chose one or more ice-creams, with quantities more than one for each of the variety chosen.
To calculate the bill parlor manager selects the appropriate check boxes according to the
verities of ice-cream chosen by the customer and enter their respective quantities. Write Java
code for the following:

a. On the click event of the button ‘Calculate’, the application finds and displays the total bill
of the customer. It first displays the rate of various ice-creams in the respective text fields. If
a user doesn’t select a check box, the respective ice-cream rate must become zero. The bill is
calculated by multiplying the various quantities with their respective rate and later adding
them all.

b. On the Click event of the clear button all the text fields and the check boxes get cleared.

c. On the click event of the close button the application gets closed.

Ans: (a)

private void jBtncalculateActionPerformed(java.awt.event.ActionEvent evt)

if(jchkStrawberry.isSelected()==true)

jTxtPriceStrawberry.setText("35");

else

jTxtPriceStrawberry.setText("0");

jTxtQtyStrawberry.setText("0");

if(jChkChocolate.isSelected()==true)

jTxtPriceChocolate.setText("50");

else

jTxtPriceChocolate.setText("0");

jTxtQtyChocolate.setText("0");
}

if(jChkVinella.isSelected()==true)

jtxtPriceVinella.setText("30");

else

jtxtPriceVinella.setText("0");

jTxtQtyVinella.setText("0");

int r1,r2,r3,q1,q2,q3,a1,a2,a3,gt;

r1=Integer.parseInt(jTxtPriceStrawberry.getText());

r2=Integer.parseInt(jTxtPriceChocolate.getText());

r3=Integer.parseInt(jtxtPriceVinella.getText());

q1=Integer.parseInt(jTxtQtyStrawberry.getText());

q2=Integer.parseInt(jTxtQtyChocolate.getText());

q3=Integer.parseInt(jTxtQtyVinella.getText());

a1=r1*q1;

jTxtAmtStrawberry.setText(""+a1);

a2=r2*q2;

jTxtAmtChocolate.setText(""+a2);

a3=r3*q3;

jTxtAmtVinella.setText(""+a3);

gt=a1+a2+a3;

jTxtTotalAmt.setText(""+gt);

Ans.(b)
private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt)

jTxtPriceStrawberry.setText("");

jTxtPriceChocolate.setText("");

jtxtPriceVinella.setText("");

jTxtQtyStrawberry.setText("");

jTxtQtyChocolate.setText("");

jTxtQtyVinella.setText("");

jTxtAmtStrawberry.setText("");

jTxtAmtChocolate.setText("");

jTxtAmtVinella.setText("");

jchkStrawberry.setSelected(false);

jChkChocolate.setSelected(false);

jChkVinella.setSelected(false);

Ans: (c)

private void jBtncloseActionPerformed(java.awt.event.ActionEvent evt)

System.exit(0);

36. Read the following case study and answer the questions that follow.

TeachWell Public School wants to computerize the employee salary section.

The School is having two categories of employees : Teaching and Non Teaching. The
Teaching

employees are further categorized into PGTs, TGTs and PRTs having different Basic salary.
The School gives addition pay of 3000 for employees who are working for more than 10
years.

Employee Type Basic Salary DA HRA Deductions

(% of Basic Sal) (% of Basic Sal) (% of Basic sal)

Non Teaching 12500 31 30 12

PGT 14500 30 21 20

TGT 12500 30 30 25

PRT 11500 12 12 12

(a) Write the code to calculate the Basic salary, deductions, gross salary and net salary based
on the given specification. Add 3000 to net salary if employee is working for more than 10
years.

Gross salary=Basic salary + DA + HRA

Net salary = Gross salary – deductions

(b)Write the code to exit the application.

(c)Write the code to disable textfields for gross salary, deductions and netsalary.

Ans: (a)

double bs=0,da=0,net=0,ded=0,gross=0,hra=0;

if (rdnon.isSelected()==true)

bs=12500;

da=(31*bs)/100;

hra=(30*bs)/100;

ded=(12*bs)/100;

else if (rdpgt.isSelected()==true)

bs=14500;
da=(30*bs)/100;

hra=(30*bs)/100;

ded=(12*bs)/100;

else if (rdtgt.isSelected()==true)

bs=12500;

da=(21*bs)/100;

hra=(30*bs)/100;

ded=(12*bs)/100;

else if (rdprt.isSelected()==true)

bs=11500;

da=(20*bs)/100;

hra=(25*bs)/100;

ded=(12*bs)/100;

gross=bs+da+hra;

net = gross – ded;

if(chk10.isSelected()==true)

net=net+3000;

tfded.setText(“ ”+ded);
tfgross.setText(“ ”+gross);

tfnet.setText(“ ”+net);

tfbs.setText(“ ”+bs);

Ans:(b)

System.exit(0);

Ans:(c)

tfgross.setEditable(false);

tfded.setEditable(false);

tfnet.setEditable(false);

37. ABC School uses the following interface built in java to check the eligibility of a student
for a particular stream from science, commerce and humanities. The user first enters the total
percentage and selects the desired stream by selecting the appropriate option button. An
additional 5% is marks is given to students of NCC. Write Java Code for the following

a. On Action event of the button ‘Calc Percentage’ Net percentage of the student is

calculated and displayed in the appropriate text filed. Net percentage is same as that of

the actual percentage if the student doesn’t opts for NCC otherwise 5% is added to actual
percentage.

b. On Action event of the button ‘Result’, the application checks the eligibility of the

students. And display result in the appropriate text field. Minimum percentage for science is
70, 60 for commerce and 40 for humanities.

c. On the Click event of the clear button all the text fields and the check boxes get cleared.

d. On the click event of the close button the application gets closed.

Ans:

a.

private void jBtnCalcPerActionPerformed(java.awt.event.ActionEvent evt)

int p;
p=Integer.parseInt(jTextField2.getText());

if (jCheckBox1.isSelected())

p=p+5;

jTextField3.setText(Integer.toString(p));

b.

private void jBtnResultActionPerformed(java.awt.event.ActionEvent evt)

int p;

p=Integer.parseInt(jTextField3.getText());

if( jRadioButton1.isSelected())

if ( p>=70)

jTextField4.setText(“Eligible for all subject”);

else

jTextfield4.setText(“Not Eligible for science”);

else if( jRadioButton2.isSelected())

if ( p>=60 )

jTextField4.setText(“Eligible for Commerce and Humanities”);

else

jTextfield4.setText(“Not Eligible for Science and Commerce”);

else
{

if ( p>=40 )

jTextField4.setText(“Eligible for Humanities”);

else

jTextfield4.setText(“Not Eligible for any subject ”);

c.

private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt)

jTextField1.setText(“ “) OR jTextField1.setText(null)

jTextField1.setText(“ “) OR jTextField1.setText(null)

jTextField1.setText(“ “) OR jTextField1.setText(null)

jTextField1.setText(“ “) OR jTextField1.setText(null)

jCheckbox1.setSelected(false);

d.

private void jBtnCloseActionPerformed(java.awt.event.ActionEvent evt)

System.exit(0);

Unsolved Questions:

1. Describe the relationship between properties, methods and events.

2. What is container tag?

3. What does a getPassword() method of a password field returns?


4. What will be the contents of jTextArea1 after executing the following statement: 1

5. jTextArea1.setText("Object\nOriented\tProgramming");

6. What is difference between jRadioButton and jCheckBox?

7. What does a JList fire when a user selects an item?

8. What is Layout Manager? Discuss briefly about layout managers offered by NetBeans?

9. Name three commonly used properties and methods of the following controls.

10. (a) text field (b) text area (c) label (d) Check Box (e) button.

11. What is dispose() used for ?

12. What is the difference between-

13. (a) Text field & Text area

14. (b) List & Combo

15. (c) Radio Button & Check Box

16. What is the significance of following properties of a text area ?

17. (a) lineWrap (b) wrapStyleword

18. What is the significance of a button group ? How do you create a button group ?

19. Discuss about some commonly used properties of lists and a combo boxes.

20. What methods obtains the current selection of a combo box ? Give a code example.

21. The FOR U SHOP has computerized its billing. A new bill is generated for each
customer. The shop allows three different payment modes. The discount is given based on the
payment mode.

a) Write the code for the CmdClear Button to clear all the Text Fields.

b) Write the code for the CmdCalc Button to display the Discount Amount and Net Price in
the TxtDisc and the TxtNet Text Fields respectively.

11. What will be the output of the following code

StringBuffer city = new StringBuffer(“Madras”);

StringBuffer string = new StringBuffer();

string.append(new String(city));
string.insert(0,”Central”);

string.out.println(string);

Ans: CentralMadras.

12. Give the output of the following program:

class MainString

{ public static void main( String agrs[])

{ StringBuffer s = new StringBuffer(“String”);

if(s.length() > 5) && (s.append(“Buffer”).equals(“x”);

System.out.println(s);

Ans: StringBuffer.

13. What is the output of the following code fragment if “abc” is passed as argument to the
func()?

Public static void func(string s1)

String s = s1 + “xyz”;

System.out.println(“s1=” + s1);

System.out.println(“s = “ +s);

Ans: s1= abc

s =abcxyz

14.What are the access specifiers in Java? Expalin.

Ans: The Access Specifiers control access to members of class from / within Java Program.
Java

supports various Access Specifiers to control the accessibility of class members.


ı Private : A variable or method declared as private, may not be accessed outside of the class.
Only

class member can access them, since they are private to others.

ı Protected: Protected members can be accessed by the class members and subclasses
(derived

classes) and current package, but they are not accessible from beyond package or outside.

ı Public: Class members declared as public, are accessible to any other class i.e. everywhere ,
since

they are public.

ı Package (default): If no any specifier is mentioned, default or friendly access is assumed.


Class

member may be accessed by any other Class members available in the same package, but not

accessible by the other classes outside the package, even subclasses.

15. What do you meant by private, public, protected, package(friendly) access specifiers?

Ans: Private Access Specifier

Members declared as private are accessible by the members of the same class, since they are
private.

A private key word is used to specify.

//e.g to demonstrate private specifier.//

class abc

{ private int p;

private void method1()

{ p=10;

system.out.print(“I am Private method”);

class xyz
{……….

void method2()

{ abc x = new abc();

x.p =10;

x.method1() ;

Protected Access Specifier

Protected members are accessible by all the classes in the same package and sub-classes
(same of different packages). A protected key word is used to specify.

Package mypackage;

class abc

{ protected int p;

protected void method1()

{ p=10;

system.out.print(“Protected

method”);

class xyz

{……….

void method2()

{ abc x = new abc();

x.p =10;

x.method1() ;

}
}

Lets another Package…

package yourpackage;

import mypackage.*;

class pqr extends abc

{ void method3()

{ abc x=new abc();

pqr y=new pqr();

x.p=10;

x.method1();

y.p=10;

y.method1();

Public Access Specifier

Public Members can be access at anywhere i.e. same or different package. A public key word
is used to specify.

packagemypackage;

class abc

{ public int p;

public void method1()

{ p=10;

system.out.print(“Public method”);

}
package yourpackage;

import mypackage.* ;

class xyz

{……….

void method2()

{ abc x = new abc();

x.p =10;

x.method1() ;

Package (friendly) Access Specifier

If no specifier is explicitly specified, Java assumes default (friendly) access i.e. all the
members are

accessible in all other classes of the same package only, since they are trusted or

friends. This is called Package level access. No any key word is used to specify default
access.

package mypackage;

class abc

{ int p;

void method1()

{ p=10;

system.out.print(“Package method”);

class xyz

{……….
void method2()

{ abc x = new abc();

x.p =10;

x.method1() ;

16. What do you understand by Library in Java?

Ans: A library is readymade and reusable component/codes that can be used in a program to
perform predefined task.

ı Some commonly used Java libraries are Math Library, String Library, Utility Library and IO
Library etc.

ı You can use import statement at the top of the program to include the Java libraries.

import java.io.*;

ı The java.lang is the default imported library

You might also like