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

Oop

Here are the key differences between classes and objects in Java: - A class is a blueprint or template that defines the attributes and behaviors of an object. It can contain fields and methods. - An object is an instance of a class. When a class is instantiated, memory is allocated and the fields and methods are initialized for that object. - Classes are static definitions while objects are runtime entities that occupy space in memory. - Classes are used to create objects. The same class can be used to create multiple objects that may have different field values but share the same behaviors defined in the class. - Fields define the attributes/state of an object while methods define the behaviors. Objects can access and modify their own

Uploaded by

sadani1989
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)
207 views

Oop

Here are the key differences between classes and objects in Java: - A class is a blueprint or template that defines the attributes and behaviors of an object. It can contain fields and methods. - An object is an instance of a class. When a class is instantiated, memory is allocated and the fields and methods are initialized for that object. - Classes are static definitions while objects are runtime entities that occupy space in memory. - Classes are used to create objects. The same class can be used to create multiple objects that may have different field values but share the same behaviors defined in the class. - Fields define the attributes/state of an object while methods define the behaviors. Objects can access and modify their own

Uploaded by

sadani1989
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/ 53

CLASS

1. Why does everything have to be in a Class?

Ans :- We have put everything in a class because of the JVM ‘s work. JVM Complies the java
byte code in to ‘a .class’ file. When we compile a Program whatever the code we put in class of a
package in java are going to convert into machine code and after that the program will run.

2. Do I have to put a main in every class I write ?


Ans :- No I can’t put main in every class I write .It is a static method so we
put it in only one class. It will be called without using instance. There
is no need of create an object to call it so if we put in every class it is
difficult to identify the main method of different class. JVM can call it
from anywhere.

3. Correct the error in following


code. classVarName
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}; - There is extra semicolon.
4. State differences between class andobject.
Ans:- Object is the instance of class and it is an runtime entity that has state
andbehavior while collection of object is called class.
Class have different methods and codes while object can only call the
method or variable of class.

5.WHO AM I?
USE FOLLOWING
(Class, Method, Object, Instance Variable)
a. I am compiled from a .javafile . Class
b. My instance variable values can be different from my buddy’s values. Object
c. I behave like a template. Class
d. I like to do stuff. Method
e. I can have many methods. Class
f. I represent ‘state’. class
g. I have behaviors. object
h. I am located in objects. class
i. I live on the heap. Instance Variable
j. I am used to create object instances. Instance Variable
k. My state can change.
l. I declare methods. class
m. I can change at runtime. Object

5. Fill in the blanks.

int x=1;
While(x<3) {
System.out.print (“Doo”);
System.out.print (“Bee”);
x=x+1;
}
If(x ==3) {
System.out.print (“Doo”);
}
}
}

6. CodeMagnets
A working java program is all scrambled up on the fridge. Can you reconstruct the
code snippets to make a working java program that produces the output listed below?
Some of the curly braces fell on the floor and they were too small to pick up, so feel free
to add as many of those as you need!
Class shuffle{
Public static void main(String[] args){
int x=3;
System.out.println(“% java shufflel”);
while(x>0)
{
if(x>2)
{
System.out.print(“a”);
}
x=x-1;
System.out.print(“-“);
if(x==2)
{
System.out.print(“b c”);
}
x=x-1;
System.out.print(“-“);
if(x==1)
{
System.out.print(“d”);
x=x-1;
}
}}}

7. "BE the compiler".


Each of the Java files on this page represents the complete source file. Your job is to
play compiler and determine whether each of these files will compile. If they won't
compile. how would you fix them?
A. Above code can be compiled.

B. Above code can’t be complied because it has no class.

C. Above code can be compiled.

8. State weather following are true or false.


a. The name of Java program file must match the name of the class with
extension.java.
:-TRUE
b. Declaration can appear anywhere in the body if a Java method.:-TRUE
c. Import statement always the first statement in java.:-FALSE
9. A short Java program is listed below. One block of the program is missing. Your
challenge is to match the candidate block of code (on the left), with the output that
you'd see if the block were inserted. Not all the lines of output will be used, and some of
the lines of output might be used more than once. Draw lines connecting the candidate
blocks of code with their matching command-line output. (The answers are at the end of
the chapter).

10. Pool Puzzle


Your job is to take snippets from the pool and place them into the blank lines in the
code. You may use the same snippet more than once, and you won't need to use all the
snippet. Your goal is to make classes that will compile and run and produce output
listed.
Class PoolPuzzleOne{
Public static void main (String [] args){
int x=0;
while (x<1) {
System.out.print(“a”);
if(x<1){ System.out.print(“ “);}
System.out.print(“n”);
if(x<3){System.out.print(“oise”);
x=x+1 ;}
if(x==1){System.out.print(“annoys”)’;}
if(x<4){System.out.print(“an”);}
System.out.println(“”);
System.out.print (“oyster”);
}
}
}
METHODS
1. What happens in Integer.parselnt if the thing you pass isn't a number? And does it
recognize spelled-out numbers, like “three"?

Ans :- If we pass anything other than numerical value in Integer.parseInt it will show error.And it

Will not recognize the spelled-out numbers.

2. What happens if the argument you want to pass is an object instead of aprimitive?

3. Can a method declare multiple return values? Or is there some way to return more
than onevalue?

4. Do I have to return the exact type, declared?

5. Do I have to do something with the return value of a method? Can I Just Ignore it?

6. What about method parameters? How do the rules about local variables apply to them?
7. Do the following.

8. BE the compiler
Each of the Java files on this page represents a complete source file. Your job is to play
compiler and determine whether each of these files will compile. If they won't compile.
how would you fix them, and if they do compile. what would be their output?
10. A bunch of Java components, in full costume, are playing a party game ,Who am I.
They give you a clue, and you try to guess who they are, based on what they say.
Assume they always tell the truth about themselves. If they happen to say something
that could be true for more than one guy, then write down all for whom that sentence
applies. Fill In the blanks next to the sentence with the names of one or moreattendees.
Tonight's attendees:
Instance variable, argument, return, getter, setter ,encapsulation, public, private,
pass by value, method

1. A class can have any number ofthese.:


2. A method can have only one of these.:
3. This can be Implicitly promoted.:
4. I prefer my Instance variables private.:
5. It really means 'make a copy'.:
6. Only setters should update these.:
7. A method can have many of these.:
8. I return something by definition.:
9. I shouldn't be used with instance variables.:
10. I can have many arguments.:
11. By definition, I take one argument.:
12. These help create encapsulation.:
13. I always fly solo.:

11. MixedMessages
A short Java program is listed to your right. Two blocks of the program are missing.
Your challenge is to match the candidate blocks of code (below), with the output that
you'd see if the blocks were Inserted. Not all the lines of output will be used, and some of
the lines of output might be used more than once. Draw lines connecting the candidate
blocks of code with their matching command-line output.
VARIABLES

2. In my other language can do a boolean test on an Integer. In Java, can I say


something like: int x =1;
while (x) { }

3. Find errors in followingdeclaration.


a. Intx;:
b. double=p,q;:
c. finalpi=3.142;:
4. Find errors in followingcode.
a. public static voiddisplay()
{
int x=123456;
float
f=100.12;
System.out.println("float value="+f);
}

b. public static voiddisplay()


{
int
i=123;
byte b=i;
System.out.println("value og Byte variable ="+b);
}
LOOPS

1. Discuss two different style of for


loop.

2. BE theJVM.
The Java file on this page represents a complete source rue. Your job is to play
JVM and determine what would be the output when the program runs?
3. CodeMagnets
A working Java program Is all scrambled up on the fridge . Can you reconstruct
the code snippets to make a working Java program that produces the output listed
below? Some of the curly braces fell on the floor and they were too small to pick up,
so feel free to add as many of those as you need!
4. A short Java program is listed below. One block of the program is missing. Your
challenge is to match the candidate block of code (on the left), with the output that
you'd see If the block were inserted. Not all the lines of output will be used, and some
of the lines of output might be used more than once. Draw lines connecting the
candidate blocks of code with their matching command-lineoutput.
CLASS AND
OBJECT

1. Each of the Java files on this page represents a complete source file. Your job is
to play compiler and determine whether each of these files will compile. If they
won’t compile, how would you fix them, and if they do compile, what would be
their output?
A
class TapeDeck {
boolean canRecord =
false; void playTape() {
System.out.println(“tape playing”);
}
void recordTape() {
System.out.println(“tape
recording”);
}
}
class TapeDeckTestDrive{
public static void main(String []
args) { t.canRecord = true;
t.playTape();
if (t.canRecord == true)
{ t.recordTape();
}
}
}
B.

class DVDPlayer {
boolean canRecord =
false; void recordDVD() {
System.out.println(“DVD recording”);
}
}
class DVDPlayerTestDrive {
public static void main(String [] args) {
DVDPlayer d = new
DVDPlayer(); d.canRecord =
true;
d.playDVD();
if (d.canRecord == true)
{ d.recordDVD();
}
}
}

2. CodeMagnets
A working java program is all scrambled up on the fridge . Can you reconstruct
the code snippets to make a working java program that produces the output
listed below? Some of the curly braces fell on the floor and they were too small to
pick up, so feel free to add as many of those as you need!
3. Pool Puzzle
Your job is to take snippets from the pool and place them into the blank lines in the
code. You may use the same snippet more than once, and you won't need to use all the
snippet. Your goal is to make classes that will compile and run and produce
outputlisted.

public class EchoTestDrive {


public static void main(String []
args) { Echo e1 = new Echo();

int x = 0;
while( ){
e1.hello();
if ( ){
e2.count = e2.count
+1;
}
if ( ){
e2.count = e2.count + e1.count;
}
x = x + 1;
}
System.out.println(e2.count);
}
}
class {
int = 0;
void {
System.out.println(“helloooo... “);
}
}
4. JavaCross
let's give your right brain something to do. It's your standard crossword, but almost all
of the solution words are from chapter 1.Just to keep you awake, we also threw in a few
(non-Java) words from the high-tech world.

Across
4. Command-line invoker
6. Back again?
8. Can't go bothways
9. Acronymfor your laptop'Spower
12. numbervariabletype
13. Acronym for achip
14. Saysomething
18. Quite a crew ofcharacters
19. Announce a new class ormethod
21. What'sa prompt good for?

Down
1. Not an integer (or your boat)
2. Comebackempty-handed
3. Openhouse
5. 'Things' holders
7. Until attitudes improve
10. Source code
consumer 11 . Can't pin
it down
13. Dept .of LAN jockeys
1S. Shocking modifier
16. Just gona have one
17.How to get things
done
20. Byte codeconsumer
CONSTRUCTOR

1. Why do you need to write a constructor if the compiler writes one foryou?

2. How can you tell a constructor from a method? Can you also have a method
that's the same name as theclass?

3. Are constructors inherited? If you don't provide a constructor but your


superclass does , do you get the superclass constructor instead of thedefault?

4. Do constructors have to bepublic?

5. How could a private constructor ever be useful? Nobody could ever call It, so
nobody could ever make a newobject?
6. Match thefollowing.

7. Give the output of following withreason.


8. Match thefollowing.
POLYMORPHISM AND INHERITANCE
1. Consider following code and answer thequestions.

a) How many instance variable does Surgeonhave?


b) How many instance variable does FamilyDoctorhave?
c) How many methods does Doctorhave?
d) How many methods does Surgeonhave?
e) How many methods does FamilyDoctorhave?
f) Can FamilyDoctor dotreatPatient()?
g) Can FamilyDoctor domakeIncision()?
2. Put a check next to the relationships that makesense.

3. We know how subclass gets to inherit a superclass method, but what if the super class
wants to use the subclass version of themethod?

4. In a subclass, what if I want to use both the superclass version and my overriding
subclass version of a method? In other words, I don't want to completely replace the
superclass version, I Just want to add more stuff toit.
5. Are there any practical limits on the levels of subclassing? How deep can yougo?

6. Hey, I just thought of something... if you don't have access to the source code for a
class, but you want to change the way a method of that class works, could you use
subclassing to do that? To extend the "bad" class and override the method with your
own bettercode?

7. Can you extend any class? Or is it like class members where if the class is private you
can't inheritit.

8. Why would you ever want to make a final class? What advantage would there be in
restricting a class from being subclassed?

9. Can you make a method final, without making the whole classfinal?
10. MixedMessages
A short Java program is listed below. One block of the program is missing! Your
challenge is to match the candidate block of code (on the left),with the output that You'd
see if the block were inserted. Not all the lines of output will be used, and some of the
lines of output might be used more than once . Draw lines connecting the candidate
blocks of code with their matching command-line output.

11. BE theCompiler
"Which of the A-B pairs of methods listed on the right, if inserted into the classes on the
left. would compile and produce the output shown? (The A method inserted into class
Monster, the B method inserted into classVampire.)
12. PoolPuzzle

13. Correct the code for overloading


Methods. public classFigure
{
public String draw(String s)
{
return "FigureDrawn";
}
public void draw(String s) { }
public void draw (double f) {}
}
ABSTRACT CLASS AND INTERFACE
1. What is point of an abstract method?

2. Interface does not give you multiple inheritance because you can’t put any
implementation code in them. If all methods are abstract, what does an interface
really youbuy?

3. How do you know whether to make a class, a subclass, an abstract class, or an


interface?

4. What if you make a concrete subclass and you need to override a method, but
you want the behavior in the superclass version of the method? in other words,
what if you don’t need to replace the method with an override, but you just want
to add to it with some additional specific code.
5. On the left you'll find sets of class diagrams. Your job is to turn these into
valid Java declaration. We did number 1 for you.
6. On the left you will find sets of class and interface declarations. Your job is to draw
the associated class diagrams on the right. What did the first one for you. Use a dashed
line for "implements" and a solid line for"extends".
7. PoolPuzzle

8. Will following code


compilesuccessfully? public
interfaceFamousLine
{
void ShowLine()
{
System.out.println("Show Line");

}
}
GARBAGE COLLECTOR

1. BE the
GarbageCompiler.
Which of the lines of code on the right, if added to the class on the left at point A,
would cause exactly one additional object to be eligible for the Garbage
Collector? (Assume that point A will call more methods) will execute for a long
time, giving the Garbage Collector time to do its stuff.)
2. In this code example, several new objects are created. Your challenge is to find
the object that is 'most popular; i.e. the one that has the most reference variables
referring to it. Then list how many total references there are for that object, and
what they are! We'll start by pointing out one of the new objects, and its
referencevariable
STATIC AND FINAL KEYWORDS

1. What if you try to call a non-static method from a static method, but the non-static
method doesn't use any instance variables. Will the compiler allowthat?

2. I could swear I've seen code that calls a static method using a reference variable Instead
of the classname.

3. A static method can't access a non-static variable. But can a non-static method access a
static variable?

4. Why would I want to make a class final? Doesn't that defeat the whole purpose ofOO?

5. Isn't it redundant to have to mark the methods final If the class isfinal?
6. BE thecompiler
The Java file on this page represents a complete program. Your job is to play with
compiler and determine whether this file will compile. If it won't compile. how would you
fix it. and if it does compile. what would be its output?
7. Your Job is to decide whether each of the following statements Is true orfalse.
1. To use the Math class, the first step is to make an instance ofit.:-
2. You can mark a constructor with the static keyword.:-
3. Static methods don't have access to instance variable state of the 'this' object.:-
4. It is good practice to call a static method using a reference variable.:-
5. Static variables could be used to count the instances of a class.:-
6. Constructors are called before static variables are initialized.:-
7. MAX_SIZE would be a good name for a static final variable.:-
8. A static initializer block runs before a class's constructorruns.:- _
9. If a class is marked final, all of its methods must be marked final.:-
10. A final method can only be overridden if its class is extended.:-
11. There is no wrapper class for boolean primitives.:-
12. A wrapper is used when you want to treat a primitive like an object.:-

8. Analyze the following twocodes.


9. Find out the legal code from followingcode.

10. What if I need global variables andmethods?


EXCEPTION HANDLING
1. Why doesn't the compiler care about those runtimeexceptions?

2. State whether following are True orfalse.


a. Try block must be followed by a catch and a finally block.:-
b. If you write a method that might cause a compiler-checked exception, you must
wrap that risky code in a try catch block.:-
c. Catch blocks can bepolymorphic.:-
d. Only compiler checked exceptions can becaught.:-
e. If you define a try catch block, a matching finally block isoptional.:-
f. If you define a try block you can pair it with a matching catch or finally block
orboth.
:-
g. If you write a method that declares that it can throw acompiler.:-
h. Checked exception you must also wrap the exception throwing code in a try
catch block.:-
i. The main() method in your program must handle all unhandled exceptions
thrown to it. :-
j. A single try block can have many different catchblocks.:-
k. A method can only throw one kind ofexception.:-
l. Finally block will run regard less of whether an exception isthrown.:-
m. Finally block can exist without a tryblock.:-
n. Try block can exist by itself without, a catch block or finallyblock.:-
o. Handling an exception is sometimes referred to asducking.:-
p. The order of catch blocksnevermatters.:- _
q. Method with a try block and finally block can optionally declare theexception.
:-
r. Run time exceptions must be handled ordeclared.:-
3. Code magnets
A working java program is all scrambled up on the fridge . Can you reconstruct the
code snippets to make a working java program that produces the output listed below?
Some of the curly braces fell on the floor and they were too small to pick up, so feel free
to add as many of those as youneed!
4. Flow control
Look at the code to the left. What do you think the output of this program would be?
What do you think it would be if the third line of the program were changed to: string
test=="yes";?Assume ScaryException extendsexception.
PACKAG
E

1. Why does there have to be a full name? Is that the only purpose of apackage?

2. How does a full name really help? What's to prevent two people from giving a
class the same packagename?

3. Does import make my class bigger? Does it actually compile the imported class
or package into mycode?

4. How come I never had to import the String class? OrSystem?

5. The method draw() in NewCircle has been set as private. Class SamePackage is
in the same package as NewCircle. Will the class be able to use themethod?
package circle;
import
circle.NewCircle; Class
SamePackage
{
public static void main(String[] args)
{
NewCircle nc= new
NewCircle(); nc.draw();
}
}

6. Given below are twofiles:


Employee.java

package purchase;
public class
Employee
{
protected double age=35.00;
}

Company.java

import
purchase.Employee
public class Company
{
public static void main(String[] args)
{
Employee e= new Employee();
System.out.println("Age="+e.ag
e);
}

}
THREAD

1. In java a thread can be createdby

A. Extending the ThreadClass


B. Implementing Runnableinterface
C. Both of theabove

2. When a class extends the Thread class, itshouldoverride method of Thread


class to start thatthread.

A. start() C. run()
B. init(). D.go()

3.What will be the output of the following programcode?

A. The program does not compile.

B. The program compiles fine,but it does not print anything because t does not
invoke the run()method.

C. The program compiles and runs fine and display test on theconsole.

4. Analyze the followingcode.

A. The program will not compile because it does not implement the run()method.

B. The program will not compile because it does not contain abstractmethods.

C. The program compilesfine.

D. None of theabove.

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


A. run-testrun-test

B. run-test

C. compilationfails

D. runtimeerror

6. Which of these method of Thread class is used to Suspend a thread for a period
oftime?

A. sleep()
B. terminate()
C. suspend()
D. stop()

7. Which function of pre defined class Thread is used to check weather current
thread being checked is stillrunning?

A. isAlive()
B. Join()
C. isRunning()
D. Alive()

8 . Which of the following are methods of Thread class?

A. yield()
B. sleep(longmsce)
C. go()
D. stop()
9. What notify() methoddo?

A. Wakes up one thread that is waiting on this object'smonitor.


B. Wakes up all threads that are not waiting on this object'smonitor.
C. Wakes up all threads that are waiting on this object'smonitor.

10. Which keyword when applied on a method indicates that only one thread
shouldexecute the method at atime?

A. final
B. synchronized
C. static

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy