Sunteți pe pagina 1din 35

Ob|ect concepts

Q: Whut ls un ob|ect ln Juvu?


A: In Java the 0becf class is the ultimate
superclass oI every other object type. All objects are
extended Irom the 0becf class, either directly or by
inheritance through any number oI parent classes. II a
class does not explicitly extend any named class, it
implicitly extends the 0becf class. An object with a
small o is the word used to describe an instance oI a
Java class.
Q: Whut's the dlfference between u cluss und un ob|ect ln Juvu?
A: A Java class is a deIinition or model oI an object
type. A class has a speciIic set oI Iields, methods and
constructors with distinct argument types. Any object
that IulIills a class deIinition directly or by inheritance
has a set oI properties and behaviour that is common to
all instances oI the class. In this sense, a class is a set oI
things that are alike.
In Java concrete classes also provide a code
implementation that can be instantiated to create an
object reIerence. An instance oI a class directly IulIills
its own deIinition, it also IulIills any superclass
deIinitions too.
The Java Virtual Machine creates static reIerences to
classes when it runs a Java program. Classloaders make
the public static Iields and methods oI classes available
to the runtime system whether any instance exists or
not. When a constructor is called, the class returns an
instance oI the object it represents.
Q: Whut's the dlfference between un lnstunce und un ob|ect?
A: When you create a Java object by calling its
constructor, the object reIerence that is returned is
called an instance. This means there is little diIIerence
between the two terms. The word instance is usually
used when we talk about the process oI object creation
or instantiation, it is a single reIerence to an object. The
word object can also be used to talk collectively about
the general properties and behaviour oI a Java object.
Q: Whut ls u concrete ob|ect?
A: The term concrete class is used to describe a class
that can be instantiated to Iorm an object instance in the
Java Runtime Environment (JRE). A concrete object
would be an instance oI a concrete class and makes
better sense in contrast with abstract classes and
interIaces, which cannot be instantiated in their own
right, only by extension or implementation by a
concrete class.
Q: Whlch ls the ob|ect ln 1es1 11 = neW 1es1{)?
A: In this example the variable f1 holds a reIerence
to an object oI the class fesf, which is also known as
an instance oI the class fesf.
&nderstundlng constructors
Q: Whut ls u constructor?
A: A constructor is a special class method that is used
to create an instance oI the class. A constructor method
is named aIter the class it belongs to and may have
arguments. The constructor returns an instance oI the
class, which is an object you can use in your Java
program.
The constructor is called without reIerring to an
instance oI the class. When you use the 3eW keyword
Iollowed by the name oI the class with parentheses, the
Java compiler knows this is a constructor call Ior the
class. The class instance it returns is normally assigned
to a variable with an appopriate type, as below. You
can call the constructor as many times as you like and it
should always return an instance.
0becf obecfT3sfa3ce = 3eW 0becf|}
Q: Whut ls the dlfference between u constructor und un ob|ect?
A: A constructor is a special type oI method that you
use to create an instance oI a class. An object is another
name Ior an instance oI a class. II you think oI a Java
source Iile as a plan or design Ior a component in a
larger machine, when you call a class constructor it is
like an instruction to the Java runtime system to say
"make one oI these". The runtime system returns an
object based on that design which you can use in your
Java program. You can call a constructor as many times
as you want to get multiple instances oI an object,
which each exist independently but can also have
linked behaviour and properties.
The Java statements in a constructor are intended to
prepare a new object Ior the work it will do in a Java
program. The constructor should ensure that the object
has all necessary input arguments, conIigure itselI Ior
use and set up any linkages and dependencies with
other Java objects.
Q: Whut ls the dlfference between u method und u constructor?
A: Methods and constructors are quite similar in
nature, you can think oI a constructor as a special type
oI static method that implicitly returns an instance oI
the relevant class. Methods have an explicit return type
in their signature that tells you what type oI object or
primitive the method will return, or ;o1d iI none. A
constructor has no explicit return type because it
always returns an instance oI the class. In most other
ways constructors are like methods, they have the same
visibility modiIiers and may have zero, one or more
arguments.
One notable property oI constructors is that the Java
compiler will automatically insert a call to the no-
argument superclass constructor unless you explicitly
add a superclass constructor statement. This
arrangement will create a compilation error iI the
superclass does not have a visible no-argument
constructor, in which case you must make the
superclass constructor visible or add call to an
alternative superclass constructor.
pub11c c1ass Examp1e exfe3ds Supec1ass {
pub11c Examp1e|} {
// Tmp11c1f1y ca11s fhe supec1ass co3sfucfo Supec1ass|}
}
pub11c Examp1e|f13a1 13f paam} {
// Supesedes 1mp11c1f ca11 fo supec1ass co3sfucfo
supe|paam}
}
}
Q: How do I lnvoke u constructor?
A: Java object constructors are invoked by putting the
3eW operator beIore the class name and enclosing any
constructor argument reIerences in parentheses aIter it.
A Iundamental case is the 0becf class, which is
invoked as Iollows.
Q: How cun I cull u constructor from u constructor?
A: When you have a number oI constructors in a
class you can call them using fh1s|} in a similar way
to the superclass constructor supe|}. For instance, iI
you have a "good citizen" constructor that takes a
Sf13and a boo1ea3, and a shorthand version that
only takes a Sf13, you may pass a deIault value to
the two argument constructor, as below.
Q: Is lt OK to tug lnllne method culls on constructors?
A: Using a dot separator to call a method on a new
instance is a convenience technique that combines two
statements in one. There is no practical diIIerence in
the method invocation, in both cases a new instance is
created and the method is executed, but in practice the
code can create unnecessary anonymous instances and
conIuse the assignment oI the return value. For clarity
it is better to use two separate statements with obvious
assignments, as the series oI examples below illustrate.
Q: Whut does the stutement super{$anonymous) meun ln Juvu?
A: The statement supe|$a3o3ymous0} would
be used as the Iirst statement oI a class constructor, it
passes the variable $a3o3ymous0 to the superclass
constructor. It may be necessary to store or read
conIiguration details Irom the variable to properly
prepare the class Ior use, Ior example. That means that
the superclass must have a constructor with a single
argument that matches the type oI the
variable$a3o3ymous0. The variable $a3o3ymous0
must be passed as an argument to the subclass
constructor or be a static variable oI the subclass
because its reIerence must be deIined beIore the
superclass constructor is called.
Q: Why do we use stutlc lnltlullzer blocks?
A: Static initializer blocks tend to be used in classes
that have important properties and behaviour that are
accessed in a static context and may require some
runtime conIiguration. A static initializer block is
similar in nature to a class constructor, except it is
executed when the class is Iirst loaded by the Java
runtime system, beIore any instance is created. Static
initialization blocks may set the initial value oI static
variables using relatively complex logic, execute Java
statements and call other methods. Since this code runs
beIore any instance oI the host class exists, it cannot
work with instance variables or methods oI its own.
Static initializer blocks enable programmers to run
relatively complex code during class loading to prepare
a class Ior use in a purely static context, or when it
would be "too late" to run the code in a constructor call.
sfaf1c {
// Execufe sfafeme3fs du13 c1ass 1oad13
}
Ob|ect deslgn
Q: How cun I count the number of lnstunces of un ob|ect?
A: To count all instances oI a class you should create
a static 13f variable to store the number oI instances
and include an increment statement in all constructors.
You must also implement a f13a1
f13a11ze|}method that is called upon garbage
collection to decrement the count. And since multiple
instances may increment and decrement the static value
in separate threads, these statements should be enclosed
in asy3cho31zed block, as in the example below.
Q: Cun ob|ects be used ln pluce of urruys?
A: Yes, sometimes it is sensible to use an object to
carry other object reIerences instead oI an array. For
instance, you could issue an object as the return value
oI a method that must return multiple object reIerences.
Q: Whut's the dlfference between equa1s und ==?
A: The Java == operator is used to compare primitive
values such as 13f, 1o3 and boo1ea3 Ior equality;
whether the variables, values or expression on either
side oI the operator equate to the same value.
Ob|ect methods
Q: Cun I use the sume vurluble nume ln two methods?
A: It is possible to use the same variable names Ior
method local variables in two separate methods, and in
separate statement blocks, enclosed by curly braces, {
and }. Methods and statement blocks have their own
variable scope, so the Java compiler and interpreter can
maintain a distinction between the variables they
contain. Generally it is preIerable Ior variables that
represent diIIerent properties to have diIIerent names to
avoid conIusion, but it is likely that several methods
may use an index named 1 in a fo loop Ior example.
pub11c c1ass MefhodLoca1va1ab1es {
;o1d fesf03e|} {
13f fesf
}
;o1d fesfTWo|} {
13f fesf
}
}
Q: Is lt posslble to use the sume vurluble nume ln the sume method?
A: It is technically possible to use the same variable
name in separate statement blocks because the
variables are localised; the compiler can deduce Irom
their context that they are diIIerent things, see the
working example below. However, it is not advisable to
use the same variable name in multiple places,
especially within the same method, because it is
conIusing and can lead to bugs.
pub11c c1ass PepeafLoca1va1ab1es {
pub11c f13a1 ;o1d doSomefh13|f13a1 Sf13 fh13} {
1f |"fh13 o3e".equa1s|fh13}} {
13f a
// 0fhe sfafeme3fs
}
1f |"fh13 fWo".equa1s|fh13}} {
13f a
// 0fhe sfafeme3fs
}
}
}
II both variables in this example are actually used Ior
the same purpose, a single variable declaration should
be made in the main body oI the method. II the
variables are Ior diIIerent purposes, it would be better
to name them diIIerently.
Q: Whut ls the syntux for methods wlth no urgument?
A: The syntax Ior methods with no arguments is to
Iollow the method name with open and close brackets
with nothing in between. This syntax applies to static
and instance methods, and those with ;o1d, primitive
or object return types.
pub11c f13a1 ;o1d 3oAume3fs|} {
// Mefhod sfafeme3fs
}
Q: How cun I get the culler of u method?
A: In most cases it is not relevant or necessary Ior a
Java method to know the object that called it. II your
code needs to know the origin oI a method call it is
likely the method is located in the wrong host class, or
your overall program structure does not Iollow good
object oriented principles. Consider whether you can
move the method to a diIIerent host class or reIactor to
place class-speciIic code in the relevant classes.
II you Iind there really s good reason to know the
origin oI method calls, add an 0becf argument to the
method and use the efC1ass|} method to test.
Q: How does un ob|ect cull un lnner cluss method?
A: Host classes call methods on inner classes in
exactly the same way as they would on a separate class
deIined in its own compilation unit. To call an inner
class' instance method it is necessary to instantiate the
class Iirst, as below.
Q: Whut ls the dlfference between u method heuder und lts slgnuture?
A: A Java method header is the whole declaration
statement Ior a method beIore its curly braces. The
header includes the method's visibility modiIier, return
type, arguments and exceptions, as below.
pub11c f13a1 Sf13 ef0efa11s|f13a1 I11e f11e,
f13a1 Sf13 key} fhoWs T0Excepf1o3
A Java method signature is the method name and
parameters only. The order oI the parameters is
signiIicant because they may distinguish overloaded
methods by the same name.
ef0efa11s|I11e, Sf13}
Ob|ect compurlson methods
Q: When ls asode{) used?
A: The hashCode|} method is used in hash-based
data stores to get a "nearly unique" identiIier Ior each
object. The hash code is used to speed up the search
process, so should have a high probability oI being
diIIerent Irom any other instance. It is possible Ior two
hash codes to be the same, so the equa1s method is
used to make an exact match.
Q: How cun I creute u constructor to equute two other ob|ects?
A: Normally when we compare two objects we use
the Iundamental equa1s|0becf} method.
Conceptually, the equals method "belongs" to the
objects you are comparing and returns a boo1ea3 to
indicate whether they are passed a reIerence to
themselves.
Its not obvious why you would choose to make that
comparison in the constructor oI another class, which
may only return a reIerence to the new instance, not a
simple boolean response. In any case, the example
below shows how you can compare method arguments
and return a boolean, which could be reIactored Ior use
in a constructor.


--
Posted By Blogger to MyJavaHub on 11/10/2011 07:07:00 PM




--
chamu


Compller concepts
Q: Whut ls the source code for the compller?
A: The source code Ior a Java program is also known
as a compilation unit, which contains the code Ior a top
level Java class or interIace. A Java compilation unit is
usually created in the Iorm oI a Iile with a .a;a
extension and is passed to the compiler as a Iile path
reIerence.
The Java source Iile contains a header that declares the
type oI class or interIace, its "visibility" with respect to
other classes, its name and any superclass it may
extend, or interIace it implements. The body oI the
class contains variable declarations and methods that
deIine the behaviour oI the class, and any constructors
used to create an instance oI the class. A compilation
unit may also contain nested inner classes.
Q: Why ls the source flle numed ufter the cluss?
A: The Java source Iile naming convention is not a
standard speciIied by the Java language but is a
common Ieature oI Java compilers, such as a;ac, to
help locate source code. The source content oI a Java
class is known as a complaton unt. By storing the
compilation unit in a Iile that is named aIter the class,
the compiler can locate any supporting classes by name
and compile those too.
This convention also extends to package names. Most
Java compilers expect source code to be stored in
directories whose names match their package
hierarchy. Thus the source code Ior a class named
Examp1e in the package com.doma13.uf11 might
be stored in a Iile with the path
c:\sc\com\doma13\uf11\Examp1e.a;a
Q: Whlch cluss should be complled flrst?
A: Sometimes you will Iind that trial and error will
give you the answer you need. II you are using the Sun
compiler, a;ac, the compiler will compile any other
classes that your target class depends on, provided the
other source Iiles are in the same directory hierarchy as
the Iirst and the sub-directory names reIlect the
package hierarchy oI the classes.
Compller communds
Q: Whut ure the steps ln complllng u cluss?
A: Once you have written the Java source code Iile,
there is only one step required to compile it. To
compile the class Irom the command line, you need to
give the path to the compiler program, such as Sun
a;ac, and the path oI the source code Iile, like this:
Q: Whut do I type ut the commund llne to complle e11o.]ava?
A: In the simplest case, type cmd in the Windows
#un dialogue (on the Start menu) and change to the
source directory then run the a;ac command, as
below.
Q: Where ls my complled cluss flle?
A: II you are sure your class s being compiled, then
the class Iile should be output somewhere! Without any
directory argument, your compiler should place the
class Iile in the same directory as your source Iile. Use
the output directory argument to speciIy where the
class Iiles are generated, as below.
Q: How cun I complle Juvu clusses wlth puckuges on the commund llne?
A: When you plan to compile Java classes into a
package hierarchy it is best to organise your Java
source Iiles in a Iolder hierarchy that matches your
packages and use the compiler's c1asspafh or cp
argument and output directory parameter d to keep
the class Iile output organised in a separate equivalent
structure.
packae o3e
pub11c c1ass amp1ePackage0ne {
pub11c sfaf1c ;o1d ma13|Sf13( as} {
Sysfem.p13f13.ouf|"Examp1e oufpuf"}
}
}
packae fWo
pub11c c1ass amp1ePackageTWo {
// Empfy
}
Add the d command beIore the Java source Iile
reIerence, Iollowed by the path Ior the output Iolder,
and the cp command Iollowed by the common root
directory Ior your source Iiles. The examples below are
split over several lines Ior clarity, it may help to put the
commands in a batch script to experiment with.
Q: How cun I ensure my compller wlll locute the SAX puckuge?
A: One way to ensure your compiler can locate any
package it may require is to pass its path to the
compiler explicitly using the c1asspafh argument,
see the exmaple below.
Compller dlugnostlcs
Q: I get "|uvuc not recognlsed"!
A: This error means that the Windows command
shell cannot Iind the path to your Java SoItware
Development Kit installation where the a;ac
program is installed. One way to solve this is to add the
a;ac program to the system environment variable
named PATh. You can also give the Iull path to the
a;ac program in the Windows shell, e.g.
c:\Ja;aS0K\b13\a;ac c:\poecfs\a;a\MyC1ass.a;a
To add to your PATh variable, open the System
Propertes applet in the Windows Control Panel, click
the Advanced tab, then the Envronment Varables
button. In the System Varables list select the PATh
variable and then the Edt button. Type a semicolon
separator Iollowed by the path to your a;ac program
then click to save the changes and back-out. Now
you should be able to use the a;ac program without
speciIying its path.
a;ac c:\poecfs\a;a\MyC1ass.a;a
Q: I get "cunnot flnd symbol", whut's wrong?
A: There is nothing wrong with the Java source you
have given. Provided the two Java source Iiles are in
the same Iolder and it is the current working Iolder,
when you compile the he11oApp.a;a class the
Java compiler should Iind the source oI the
he11o.a;a class and compile it too.
The "cannot Iind symbol" error suggests that your Java
source Iolder is not the current working Iolder, or you
have given a c1asspafh argument that does not
match the source Iolder. The Iirst case is the most
likely. For example, iI your source Iiles are at
C:\0ocume3fs a3d Seff13s\Tesf and your
command prompt is C:\> the implicit classpath is the
root Iolder oI the C: drive. This is where the compiler
will look Ior any supporting classes and won't Iind
them there.
To solve this problem add an explicit classpath
argument Ior your test Iolder, split over two lines below
Ior clarity. Enclose Iile paths with spaces in quotes.
C:\> a;ac cp "ocumen1s and Se111ngsTes1"
"C:\0ocume3fs a3d Seff13s\Tesf\he11oApp.a;a"
Q: Whut does thls deprecutlon messuge meun?
A: The deprecation message you have seen means
that the methods you are calling have been marked with
a JavaDoc deprecation comment. When a method or
class is marked depecafed it is only advisory, not
mandatory, but the advice is given Ior good reason and
should be Iollowed. So long as deprecated methods
remain in the public API it is possible to use them, so
this approach supports legacy code and gives
developers time to amend their applications as
necessary.
Q: Whut ure undeflned und undeclured vurlubles?
A: One gets warning messages about undeIined and
undeclared variables when compiling Java classes that
have programming errors, as in the example below.
Q: Why doesn't the compller wurn ubout stuck overflow problems?
A: There are many cases oI poor runtime
programming that could potentially be identiIied at
compile time, but the number and subtlety oI the cases
gets increasingly diIIicult to address. The main purpose
oI a compiler is to produce executable byte code that is
valid according to the rules oI the programming
language, not to guard against poor programming.
Hence most compilers only validate the syntax oI the
language and the most obvious logical errors in the
code at compile time.
evelopment envlronment
Q: Whut Juvu compllers ure there?
A: There are many Java compiler implementations.
The one most developers start with is that provided
with the Sun Java SoItware Development Kit (JSDK),
named a;ac. Alternative implementations include
the Iree open source GNU Compiler Ior Java (GCJ) and
the Eclipse Compiler Ior Java, which is part oI the
Eclipse integrated development environment (IDE).
Q: How do I set the compller puth?
A: The Java compiler is a program like any other and
your operating system needs to know where to Iind the
executable Iile. The simplest way to do this is to give
the Iull path to the Java compiler in the command, as
below Ior Windows...
Q: The OS commund cd doesn't go to the Juvu dlrectory!
A: The Windows command line program cd is to
change directory, the present working directory Ior
subsequent commands, and requires a space between
program name cd and the directory path you want. The
examples below show three main ways to change
directory starting Irom the root oI the C: drive.
PEM Cha3e fo fhe oof of fhe C: d1;e
c:
cd \
PEM Pe1af1;e pafh W1fh 1ead13 s1ash
cd \dk1.5\b13
PEM Pefu3 fo oof of C:
cd \
PEM Pe1af1;e pafh, 3o 1ead13 s1ash
cd dk1.5\b13
PEM Pefu3 fo oof of C:
cd \
PEM Abso1ufe pafh
cd c:\dk1.5\b13
Q: How do I set envlronment vurlubles on
Wlndows XP?
A: For Windows 2000/XP systems, the environment
settings are edited in a special ontrol Panel applet
called System
...
Learn Java programming
Q: How do Java Iront- and back-end skill sets diIIer?
A: This is a somewhat arbitrary
distinction to make about Java
development, since applications oIten
have Iront- and back-end components
and it is important to understand how
both aspects are integrated. In general
terms, back-end development is
concerned with database storage and
retrieval, servlets, Web application
Irameworks and Enterprise Java Beans.
This requires a good understanding oI
SQL and database applications, JDBC,
network principles, servlet containers,
the HTTP protocol and an appreciation
oI concurrent programming issues.
Front-end development Ior servlets is
concerned with the delivery oI HTML
content to Web browsers, especially
Iorms, and touches on most aspects oI
markup design, Cascading Style Sheets
and Javascript. Usually, Iront-end
developers will work to visual designs
provided by others, and will implement
the work using a combination oI
Iormats including JSP, JSP tag libraries
and other template Irameworks, such as
Spring.
Front-end developers may also be
involved in creating pure Java user
interIaces Ior stand-alone Swing
applications or (less commonly these
days) the Abstract Windowing Toolkit
(AWT) Ior applets. In this case, it is
important to have a good knowledge oI
the Swing API components, their
intended use, and the data structures
they operate on.
Q: Is there a tool to type Java code and see what happens?
A: Sounds like you're looking Ior a user
interIace where you can enter Java
statements and execute them. TheBlueJ
interactive Java environment is
designed Ior people who are new to
Java programming and lets you execute
arbitrary Java statements to see how
they work.
You also need to download and install
a recent Java SoItware Development
Kit Iirst, version 6 is recommended, but
all code is handled through BlueJ.
Start BlueJ, go to the Vew menu and
the set the ode Pad visible. Type
statements in the Code Pad area and
they will be executed when you press
the Enter key. II you include
System.out.println() statements they
will automatically open a Termnal
Window to display the output, as
Iollows.
Q: How can Java restrict viruses?
A: The Java Runtime Environment
(JRE) is the plug-in soItware that runs
Java applets in Web browsers.
Normally Java applets are executed in a
so-called "sandbox" environment inside
the Web browser that prevents direct
access to the host computer's Iile
system and blocks potentially
hazardous operations.
The JRE soItware Irom Sun, Oracle
and other reputable suppliers is saIe to
install, but some versions oI the
soItware have been Iound to be
vulnerable to viruses and worms. A
standard virus checker with up to date
virus "signature" Iiles should detect and
prevent such problems.
This Virus Iound in the Java cache
directory article explains some typical
cases and how to remove the problem.
To minimise the risk oI inIections, keep
your JRE soItware up to date with the
latest Java Downloads.
Q: Can CSS support Java applets?
A: It is possible to control the position
and spacing between Java applets and
other HTML document elements using
CSS, but the CSS associated with the
Web page cannot aIIect the visual
appearance oI the applet embedded in
it.
applet, object
margin: 0.5em;
padding: 0;
}
The appearance oI Java applets is
controlled by the Abstract Windowing
Toolkit (AWT) or Swing interIace
properties deIined in the applet class. It
is possible to set the logical Iont type,
colour and background colour Ior
applet components, as well as the
internal layout.
Label label new Label("Example label");
label.setFont(new Font("SeriI", Font.BOLD, 14));
label.setForeground(new Color(0, 55, 153));
JavaFX supports a style sheet scheme
that uses a similar syntax to CSS,
attached to the Scene class.
Q: What is a good beginner's book about Java?
A: Thinking In Java by Bruce Eckel is
a good beginner's book on Java, which
is available as a Iree download too.
Java jargon
Q: What is the diIIerence between the JVM, JRE and JDK?
A: The JDK, also called the Java
SoItware Development Kit (SDK), is
the Iull suite oI tools required to
develop, package and publish Java
applications. The Sun Java SDK
includes the Iull Java class library, with
a compiler, decompiler, proIiler, JAR
signer, key signing tool and many other
tools.
Q: What's the diIIerence between JVM and JIT?
A: The Java Virtual Machine (JVM) is
a program that runs on a computer
operating system and executes Java
program code. The JVM takes the Java
code and compiles it to a Iormat that
can be run directly on the computer's
processor. The JVM controls the
interIace between the Java code and the
computer like audio soItware enables
us to play the same CD on a Windows,
Mac or GNU Linux computer.
In early versions oI the JVM, all the
Java code Ior a program had to be
loaded and compiled beIore the
program could be run. More recent
versions are optimised so that the Java
code is compiled "Just In Time"; just
beIore it is due to be executed on the
processor. This approach accelerates
program start-up, and overall
perIormance oI the Java program, but
requires an extra level oI coordination
within the virtual machine.
Q: What is the diIIerence betwen invoke and call?
A: There is no practical diIIerence in
the meaning oI "invoke" versus "call"
in Java programming, both mean that
one class executes a method or
constructor on itselI or another class. In
general terms the word invoke means to
call upon an agent Ior help or guidance,
or appeal Ior conIirmation or
corroboration, or summon an entity.
Java programs can also be thought oI as
a sequence or network oI messages that
are sent between classes to trigger
behaviour and get a response. The
metaphor is basically the same in both
cases.
Java operators and arithmetic
Q: Does the order oI the operands in matter?
A: With this sort oI question it is oIten
easiest to try it yourselI and see. You
will Iind that single boolean
comparisons are equivalent whichever
way round you have the values.
From a reader's point oI view most
people would put the "unknown"
variable Iirst because it is the subject oI
the comparison, but syntactically it
does not matter.
iI (a 10) }
Q: How do I add two numbers in Java?
A: To add two numbers in Java, use the
simple mathematical plus operator,
which may be applied to any numeric
variable type, as below:
int variable1 26;
int variable2 4;
int result variable1 variable2;
The result oI the addition does not have
to be assigned to a variable, it can also
be used anonymously in control
statements, as below.
Q: How can I add two numbers using a method?
A: For simple mathematical Iunctions a
method would usually declare the input
variables as method arguments and a
return type that matches the required
numeric type Ior the result. In the
simplest case anadd(int, int) method
would return an int value, as below:
public Iinal int add(Iinal int IirstInt,
Iinal int secondInt)
return IirstInt secondInt;
}
To add two numbers you would call the
method and assign the return value to a
variable so it can be used later.
int sum add(5, 2);
Q: How should I round a double up to an nt?
A: To round a double value up and
convert it to an int value takes two
operations. The staticMath.ceil(double)
method returns a double value that is
equal to the "next highest" integer. You
must then give an explicit down cast to
an int, as below.

Q: How can I calculate minimum, maximum and average using Java?
A: Assuming you have data values in a
Java storage structure, the key part oI
the process is to iterate through the
values, check and store the minimum
and maximum values, the running total
and number oI data points. Lets take
the simple case oI an iterator over a set
oI DataPoint objects that have an int
getValue() method.
This example has int variables Ior max,
min, count, sum and a temporary
dataValue. The initial value Iormax is
set to Integer.MINVALUE so that any
given value should exceed it, and min
is set toInteger.MAXVALUE. A Iloat
type is speciIied Ior the mean variable
since integer division is likely to result
in a Iraction and the decimal part
should be preserved.

Q: What are bitwise and bit shiIt operators?
A: Java bitwise operators act on the
binary representation oI primitive
numbers int and long. Bitwise shiIt
operators perIorm low level
mathematical actions as iI they
physically shiIt binary digits leIt and
right. The bitwise logical operators
compare numbers bit by bit and
transIorm them according to boolean
logic. The examples below show how
the 32 bit binary values are transIormed
by each operator and highlight some
signiIicant exceptions in the the use oI
shiIt operators in mathematics.

Variable scope
Q: Why does this 1or loop instantiation Iail to compile?
A: II you declare a variable in a Ior
loop without braces the Sun compiler
will Iail with the message "not a
statement", but the message is
misleading. A more appropriate error
message would be "o is already
deIined". In this case there is no
contained scope Ior the variable o, so
every pass through the loop would have
the eIIect oI declaring the variable
again and again.
// Does not compile
Ior ( ; ; ) Out o new Out();
Without braces its as iI you had written
a continuous list oI variable
declarations:
// Does not compile
Out o new Out();
Out o new Out();
...
In the example below the Ior loop
statement is enclosed in curly braces,
which gives the variable declaration
more precise scope. In this case, each
pass through the loop creates a "throw-
away" variable which is local to the
statement block.
Ior ( ; ; )
// Compiles
Out o new Out();
}
This question is not particularly to do
with the Ior loop and it makes no
diIIerence whether the loop runs once
or an inIinite number oI times. The
signiIicant point is not to do with
assignment, it is about the declaration
oI the variable and the scope the
variable has. The annotated example
below continues the case oI the Ior
loop, but the key is to compare the
diIIerent syntax that Iollows the Ior
conditions.

Class relationships and reIerences
Q: How do I call another class in the same Iolder?
A: Assuming the Java classes are in the
same package, one class should
instantiate the other to call an instance
method, or use a class name reIerence
to call a static method, as below.
public class Example
public static void main(String|| args)
Other otherInstance new Other();
otherInstance.instanceMethod();
Other.staticMethod();
}
}
Q: How do you put both Iiles in the same package to call them?
A: II two Java source Iiles are located
in the same directory and neither
explicitly declare a package name, they
are implicitly in the same deIault
package and no explicit import
statements are required between them.
Both classes can reIer to each other,
instantiate and call methods on each
other directly provided there are no
visibility modiIiers that would prevent
this.
When you create a package structure
Ior your classes these relationships get
a little more complicated. In the
simplest case you can declare that both
classes belong to the same package by
adding the same packagestatement to
the head oI both source Iiles, beIore the
class deIinition. In this case both
classes can reIer and call on each other
as with the deIault package above, no
import statements are required.
package org.example.packagename;
The convention Ior package names is to
be the reverse oI the Internet domain
associated with the project with dot
separators. The package names are
appended with a dot separator all in
lower case.
Q:
...

|Message clipped| View entire message
"uck #eply

--Q: When should I use static operations?
A: Java is an object oriented language,
so the Iirst principle is to implement the
majority oI your program through
object instances, instance variables and
methods. One area where a static
context is necessary is during program
start-up because the Java entry point
method is static: public static void
main(String||). This means that
variables and methods required during
start-up may need to be static too, but
the principle should be to create a
primary core object Ior your program
early and use that to instantiate and
interact with other object components
oI the system.
As a rule, static variables and methods
should be kept to a minimum. Static
variables are generally used Ior values
that belong to, or represent some state
oI the class as a whole, where all
instances would have the same value.
The most obvious examples are
constants like Integer.MAXVALUE,
where the value is Iixed and standard
whatever instance oI an Integer you
have, or a counter that keeps track oI a
value across all instances.
Static methods are oIten used as
utilities that are not associated with a
particular instance oI a class. For
example, static utility methods may be
used to parse an input value to another
type, as with theInteger.valueOI(String)
method, or as so-called Iactory methods
to acquire a pre-conIigured instance oI
a type, like the Calendar.getInstance()
method.
Static variables
Q: What is special about static variables?
A: A static variable is shared by all
instances oI a class. Every instance has
a reIerence to the same variable and
can modiIy it directly. Static instances
are declared with the static modiIier.
Q: I get "non-static variable this cannot be reIerenced Irom a static context"!
A: The main method must be declared
public static void because it is invoked
when the Java Virtual Machine Iirst
starts up, beIore any Java object
instances exist. The main method may
reIerence any number oI static
variables and call static methods. Any
series oI calls to other static methods
only extends this original static context.
To reIerence a non-static or nstance
variable Irom the main method, you
must Iirst instantiate the relevant
object, even iI it is the host oI the main
method itselI, as below.
Q: How can I call static class members Irom a diIIerent class?
A: Calling static members in a separate
class is very similar to calling a static
method in a separate class. Most
importantly, the static member must
have a public, package or protected
modiIier that makes it accessible to the
calling class. Use the class name, a dot
separator and the name oI the member
variable, as with the AWT Color class
properties below:
Color textColor Color.black;
Color panelColor Color.lightGray;
Static method calls
Q: What's the diIIerence in calling a method Irom a class or an object?
A: The only way that a class can call a
method without an object reIerence is
in a static context. For example, the
static main() method is invoked in a
static context, beIore any instance is
created, so any methods it calls must
also be static. The main() method may
call static methods oI its own, or oI
other classes.
One key thing about static methods is
that they must not reIerence any
instance variables or call any instance
methods because there may not be any
instance oI an object in the static
context.
When you call a method Irom an object
(more precisely Irom a reIerence to an
instance oI an object), it ensures that an
instance exists and means that all
instance variables are initialised and
can be reIerenced, and instance
methods can saIely be called. The
compiler ensures these conditions. An
instance can also call a class or static
method and variables oI its own or
other classes.
Q: How do I call a static method in a separate class?
A: To call a static method in a separate
class you should preIix the method
reIerence with the name oI the class it
belongs to, known as the host class. For
example, the String class has valueOI()
methods to convert primitive values to
strings:
String booleanString String.valueOI(true);
Q: Can I call a static method Irom an object reIerence?
A: Yes, it is possible to call a static
method Irom an object reIerence. The
object reIerence must be the host oI the
static method. The example below
constructs a new instance oI itselI, but
any other class could instantiate the
class and call its static method.
public class StaticMethodExample
public static void staticMethod()
System.out.println("Static method call.");
}
public static void main(String|| args)
StaticMethodExample object new StaticMethodExample();
object.staticMethod();
}
}
Unless you happen to have an instance
oI a class Ior other purposes, it is
generally simpler, clearer and
preIerable to use a static reIerence to
the host class.
StaticMethodExample.staticMethod();
Q: Can I call super() Irom a static context?
A: The super() method can only be
called in an object's constructor, it
cannot be called in a static context. The
only way to invoke the super() method
is to place this statement in the Iirst line
oI an object's constructor and
instantiate the object. You can then
invoke this method via the static void
main(String||) method, as below.
public class SuperConstructor extends Superclass
public SuperConstructor()
super();
}
public static void main(String|| args)
SuperConstructor object new SuperConstructor();
}
}
Q: Can I call the superclass version oI an overridden static method?
A: Static methods cannot truly be
overridden, iI you create static methods
with the same signature as those in a
superclass it will lead to conIusing
behaviour and is not recommended. It
is not possible to use thesuper keyword
in the static context oI a subclass
because it reIers to a instance. Just use
the standard static method reIerence
scheme Ior the superclass; the
superclass name, a dot separator, the
method name and arguments, as below.
public class ExampleSubclass extends ExampleSuperclass
public static void main(String|| args)
ExampleSuperclass.testMethod();
}
}
Q: This static method sure looks like it overrides the superclass!
A: Creating a static method with the
same signature as a superclass version
eIIectively des the superclass
method, it does not override it. This is a
diIIicult distinction to understand and
to detect because in several contexts the
methods behave as iI they were
overridden. The diIIerence becomes
apparent when an instance oI the
subclass is assigned to a superclass
type, as below.
public class SuperclassStatic
public static void testMethod()
System.out.println("Superclass message");
}
}
public class SubclassStatic extends SuperclassStatic
public static void testMethod()
System.out.println("Subclass message");
}
public static void main(Iinal String|| args)
System.out.println("Calling subclass method...");
testMethod();
System.out.println("Calling superclass method...");
SuperclassStatic.testMethod();
// Subclass type
SubclassStatic subStatic new SubclassStatic();
System.out.println("Calling static method on subclass type...");
subStatic.testMethod();
// Superclass type
SuperclassStatc superStatc new SubclassStatic();
System.out.println("Calling static method on superclass type...");
superStatic.testMethod();
}
}
The subclass' local call to the static
testMethod() executes its own version
and you get the subclass message. The
call to the
SuperclassStatic.testMethod() executes
the superclass version and you get the
superclass message.
When you assign an instance oI the
subclass to a SubclassStatic type
variable, the runtime system executes
the testMethod() version associated
with the varable type, so gives the
subclass message. In the last case a
subclass instance is assigned to a
variable declared as a SuperStatic type,
so thetestMethod() deIined in the
superclass is executed and gives the
superclass message.
...

S-ar putea să vă placă și