Basic java Flashcards
Do you need to import Java.lang library in a Java program
No, it is available by default
Can you have the class name of a java program different from the name of the .java file it resides in?
Yes but not in case of public classes, The file name and public class name should match else you will get a compile time error saying “class <> is public, should be declared in a file named <>.java”
How to escape a character like double quote, backslash etc.?
By putting a backslash() in front of the character to be escaped.
Scanner class
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods
should an IO class like Scanner be closed
Yes, this should be done to avoid memory leakage and can be done by calling close() method on the scanner class object
variables - private; methods - public
variables in a class should be declared as private to restrict access to them and allow access only through get and set methods. Hence methods should be declared public.
Primitive Types
boolean(True/false), byte(one byte), char(2 bytes), short, int, long, float, double
Reference types
Anything which does not belong to the primitive types is of reference type. Reference types start with a capital letter
Does reference type store the actual object
no, they store a reference to an object not the actual value of the object
constructor features
have the exact same name as the class; do not have a return type; a class can have as many constructors as needed but they should differ in parameters and/or types; once a constructor is defined the compiler won’t provide a default one, all versions of the constructors needed will have to be defined by the user
approximation in double type
For financial calculations avoid using double variables as double approximates values. Use third party libraries of bigdecimal insterad
What is input stream?
An object from which we can read a sequence of bytes is called an input stream
What is an output steam?
An object to which we can write a sequence of bytes is called an output stream
JDK
Jave development kit - Includes JRE - Needed for development in Java
JRE
Java runtime environment - needed to run Java applications
Line Comments
//
Block comments
/* … */
Javadoc comments
/** … */
line comments in a block comment
valid and no compile time error
Package naming conventions
Should be all lower case
use reverse domain name to insure uniqueness for example pluralsight.com will use com.pluralsight
Add further qualifiers to ensure uniqueness within the company/group
allowed characters for variable names
letters, numbers, dollar sign and underscore
Convention for variables names
only letters and numbers are used conventionally. Camel case is followed for casing
Four integer types with sizes
Byte - 8 bits
Short - 16 bits
Int - 32 bits
Long - 64 bits
The result of divide operation on floating point operands and integer operands
example 13.0/5.0 will result in 2.6 whereas 13/5 will give 2
The result of divide operation on floating point operands and integer operands
example 13.0/5.0 will result in 2.6 whereas 13/5 will give 2
Operator precedence
postfix then prefix then multiplicative then additive.
How are operators of equal precedence evaluated
left to right
Implicit type conversion rule for mixed integer types in an equation
Converted to largest integer type in the equation
Implicit conversion types for mixed floating types in an equation
Converted to double as double is the largest floating point type
Implicit conversion types for mixed integer and floating types in an equation
Converted to the largest floating point type in the equation
Conditional assignment
result = condition?true-value:false-value
Variables’ scope
Variables that are in scope when the block start remain in scope inside the block
Variables declared within a block are out of scope outside the blocks
Conditional logical operators
the expression at the right side of the operator is evaluated only if it is needed to determine the final result
Encapsulation
The concept of hiding internal representation of an object
visibility with no access modifiers
Also called package private. Visible only within its own package. Usable on classes and members of a class
Private access modifier
Visible only within its own class. Not usable on top level classes but only members of a class
Naming convention for classes
Should use ‘Pascal Case’. The name should be a descriptive noun without any acronyms
THIS keyword
THIS is an implicit reference to the current object
What does null represent
It represents an uncreated object
Mechanisms to establish initial states of an object
Field initializers
constructors
Initialization blocks
initial values of variables vs fields
Variables need to be explicitly initialized whereas a fields initial state is established as part of object construction(initialed to “zero” meaning int types get 0, boolean gets false, double gets 0.0, reference type gets null and so on)
What does explicit constructor do to default constructor
Once we create a user defines constructor, the default constructor is no longer available. User will have to create all the constructors needed for the class
Characteristics of initialization blocks
- Shared across all constructors
- Executes as if the code was placed at the start of each constructor
- declared by including a block of code in side brackets {} (no method name of qualifiers)
- If there are multiple initialization blocks in a class, they are called in the order in which they appear from top to bottom
order of execution of, constructors, filed initializations and initialization blocks
1) Field initialization 2) Initialization Block 3) Constructor
Where should a chained constructor call appear in a calling constructor?
Chained constructor call should be the first line in a calling constructor
Can a child class be assigned to a reference type of its parent class
Yes, but the object so obtained will have access to methods only visible to the parent class.
What happens if you declare a variable in a child class with the same name as one in its parent class?
The variable in the parent class gets hidden by the one in child class
Which overridden method is called when the reference and corresponding object are of different types
The method belonging to the type of object and not the reference is called
What annotation can be used to make sure the signature of the overridden method in child class matches that of the parent class
@override (used only at compile time to make sure the signature of the overridden methods match, no significance at runtime)
Which class is the root of the Java class hierarchy
Object class
== operator compares references, true or false
True
Super treats an object as if it is an instance of the base class
True
Syntax for defining a final class
final Class
or
final Class
Should a class be defined as abstract if a method inside it is
Yes, the class should have the qualifier abstract if at least one of its method is abstract
What does the intern method of String class do
it returns a canonical representation of a string object
What’s the mutability of wrapper classes
Wrapper classes are immutable
What is boxing?
taking a primitive type and wrapper it in a wrapper classes is called boxing. valueOf method is used generally for this
What is unboxing?
Extracting a primitive value from a wrapper class is called unboxing. xxxValue() method is generally used for this (xxx is int, char, byte etc)
Method to convert String to primitive type
parseXxx() where Xxx corresponds to the primitive type
Method to convert String to wrapper class
valueOf()
Strings are immutable, True or False
True(that why we use string builder)
What should be the order of exception types in the catch block
catch block should catch the more specific exception type first then followed by a more general type
Exceptions in java travel up the call stack, True or False?
True
What are the three ways of making sure that the throws clause of an overriding method is compatible with the throws clause of the overridden method
1) Exclude exceptions in the method signature
2) Have the same exception as the overridden method
3) Have a derived exception(e.g. throwing fileNotFoundException instead of IOException)
Where should a package declaration appear in a class file
before any type declarations
What are the 3 ways to avoid explicitly qualifying types(with full package names)
1) Types in current package do not need not be qualified
2) Types in java.lang package do not need to be qualified
3) Use type imports
Where’s the documentation for jar manifest
http://bit.ly/jarmanifest
How is start-up class identified in a JAR file
Usually it is done through manifest
What is an interface
It defines a contract that a class can confirm to. It doesn’t provide and implementation
A class can extend more than one class
False
A clas can implement more than one interface
True
Are streams bidirectional?
No, they are unidirectional
Two kinds of streams
Byte Stream - Interact as binary data
Text Stream - interact as unicode characters
Class for reading byte stream
InputStream
Class for reading text stream
Reader
InputStream and OutputStream are abstract class, true or false
True
how to associate a type to an ArrayList
ArrayList list = new ArrayList<>()
e.g. ArrayList list = new ArrayList<>()
Which collection doesn’t implement collection interface
Map
Method to get an Array out of a collection
toArray
Method to get an Array as a collection
asList
For properties files, white spaces before and after = and : signs are ignored
True
What happens if no = or : sign is provided in a property value pair
the first whitespace will be used as a key/value separator
Command to set a classpath from command prompt
set CLASSPATH=
Why do you need class paths
Java needs to know where to look for classes to load for a program or application
What delimiters are used to separate multiple classpaths from each other
windows system - ;
Unix system - :
What is the order order in which classpath folders are searched if there are more than one specified
order of appearance
command to run a java program from command prompt along with classpath name
java -cp
How to load classes in jars with classpath option on command prompt
java -cp
Running a class from within a jar with -jar option
java -jar
This loads the classes only within the jar and is used to load classes in a very controlled manner
About persistence of system properties set by setProperties method
The setProperties method changes the set of system properties for the current running application. These changes are not persistent. That is, changing the system properties within an application will not affect future invocations of the Java interpreter for this or any other application. The runtime system re-initializes the system properties each time its starts up. If changes to system properties are to be persistent, then the application must write the values to some file before exiting and read them in again upon startup
What does the logger level SEVERE specify
Numeric value - 1000
Description - Serious failure
What does the logger level WARNING specify
Numeric value - 900
Description - Potential Problem
What does the logger level INFO specify
Numeric value - 800
Description - General info
What does the logger level CONFIG specify
Numeric value - 700
Description - Configuration info
What does the logger level FINE specify
Numeric value - 500
Description - General developer info
What does the logger level FINER specify
Numeric value - 400
Description - Detailed developer info
What does the logger level FINEST specify
Numeric value - 300
Description - Specialized developer info
When is the LogManager object created and can it be changed subsequently
The LogManager object is created during class initialization and cannot be changed subsequently
What does the LogManager object does?
Maintains a hierarchical namespace of logging objects
Manages a set of logging control properties
There is a single global LogManager object that is used to maintain a set of shared state about Loggers and log services
True
How to retrieve a LogManager object
using LogManager.getLogManager()