Saturday, December 31, 2016

Number System in JAVA

Number System in JAVA

-------------------------------------------------------------------------------------------------------
To represent numbers in programming language programming language must follow a particular system called as "Number Systems".

There are four types of number system to represents numbers:

1. Binary Number System
2. Octal Number System
3. Decimal Number System
4. Hexa Decimal Number System

All the above four number system are allowed in java but the default number system is "Decimal Number System".

1. Binary Number:
To represent numbers in Binary Number system, we have to use the symbols like 0's & 1's, but the number must be prefixed either with Ob or OB.

EX:
int a = 10; --------> It is not valid number, it is decimal number.
int b = 0b1010; ----> valid
int c = 0B1010; ----> valid
int d = Ob1010; ----> invalid

Note: Binary number system is not supported by JAVA upto JAVA6 version, but it is supported by JAVA7 and above versions.

2. Octal Number:
To represent numbers in octal number system, we have to use a symbols like 0,1,2,3,4,5,6,7,8,9 but the number be prefixed with 0.

EX:
int a = 10; ------->  it is not octal number, it is decimal number.
int b = 01234; ----> valid
int c = O3456; -----> invalid
int d = 03458; -----> invalid(8 is not included in octal number)

3. Decimal Number:
To represent number in decimal number system, we have to use the numbers like 0,1,2,3,4,5,6,7,8,9. the provided number must not have any prefix value.


4 Hexa Decimal Number:
To represent number in Hexa decimal number system, we have to use the symbols like 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f but the number must be prefixed either with '0x' or '0X'.

EX:
int a = 10; -----> it is not hexa decimal number, it is decimal number.
int b = 0x1020; ---> valid
int c = 0X1020; ---> valid
int d = 0x12abcde; ---> valid
int e = 0x12efg; ----> invalid

Note : if we provide any number system in java application the compiler will recognize that number and its number system on the basis of its prefix value and compiler will convert that number into decimal number system and compiler will process that number as like decimal number.

Friday, December 30, 2016

2. Literals in java


2. Literals
-------------------------------------------------
Literals is a constant assignment to the variables.

EX:
int a = 10;
where,
int --------> dataType
a ----------> variable[identifier]
= ----------> operator
10 ---------> constant[Literal]
; ----------> special symbol/Terminator

To prepare java application, java has provided the following literal groups:

1. Integer Literal/ Integral Literals:
byte, shot, int, long -------> 10,20,30,....
char ------> 'A', '/n', '/t',.........

2. Floating point Literals:
float ------> 20.30f, 321.023f,.........
double ------> 321.12, 3642.2312,.....

3. String Literal:
String -----> "abc", "xyz",.....

4. Boolean Literal:
Boolean ------> true, false

Note: To improve readability in the literals, java7 has provided a flexibility like to include '_' symbols in middle of the number.
EX:
float f = 1_23_63_234.231f;
System.out.prinln(f);

if we compile the above code then compiler will remove '_' symbol from number, compiler will reformat that as original number, compiler will process
that number as original number only.

commands in Oracle dbms

1. show user: show user <user name>;

2. grant resource, connect to <user name>; ----> user get permission to connect with database

3. cl scr; ------> clear screen

4. select * from tab; ----> it will display list of table names, view names & index names from the current schema.

schema: users account is known as schema.
Tab: it is known as table space(storage area)

5. describe table_name(emp_info): it will display the structure of the table, like column names, data types, sizes.

6. Insert Command: this command is used to insert one record into a table at a time.
Syntax:
insert into <table> (col1, col2, col3,......)
values(val1, val2, val3......);

EX: insert into emp_info (eid, ename, sal, desg, jdate)
values(111,'ram', 10000,'developer', '26-may-96');
display: 1 row created:

Note: in the above example, no of values, no of column in the table are equal so it is not necessary to specify column name.

Note: while inserting a record, char & date type value must be written in single course.

EX: insert into emp_table
values('john', 23000, 'programmer');
display: error line 1:
not enough values.

Note: if number of values inserting are less than number of column then:
1. maintain column name
2. maintain null keyword at the place of missed value.

EX: SQL> insert into emp_info(ename, sal, desg)
values('john', 20000, 'programmer');
display: 1 row created.

EX: SQL> insert into emp_info
values(null, 'john', 20000, 'programmer', null);
display: 1 row created.

EX: SQL> insert into emp_info(sal, ename, desg)
values(2000, 'john', 'programmer');
display: 1 row created.
-----------------------------

7. Select Command:
if is a logical command, it is used to fetch data from the tables or views.
Syntax: Select col1, col2... or * or expression or value
from <table name>

EX: get employee name:
select ename from emp_info;

EX:
SQL>select ename, sal, desg from emp_info;
SQL>select * from emp_info;

Use predefined class as identifiers in JAVA

E. In java application, we are able to use all predefined class names & interface names as identifiers.

EX: 1
int Exception= 10;
System.out.println(Exception);

Status: No compilation error
Output: 10

Note: Here Exception is an int variable.
---------------

EX: 2
String String = "String";
System.out.println(String);

Status: No compilation Error.
Output: String

Note: Here First String is as String class, 2nd String as a variable, 3rd String as value of variable.
--------------

EX: 3
int System = 10;
System.out.println(System);

Status: Compilation Error.
Reason: In java application , if we declare "System" as an integer variable then in the remaining program, we must use that System as integer variable only, we must not use that System as original class name, if we use "System" as original class name then compiler will rise an error.

In the above context if wi want to use System as class name, then we have to use its "fully qualified name" providing class name along their package name is called as "Fully qualified name".

EX:
class Test
{
public static void main(String[] args)
{
int System = 10;
java.lang.System.out.println(System);
System=System + 10;
java.lang.System.out.println(System);
}
}

Status: No compilation error
Output:
10
20
---------------------------

Along with the above rules & regulations, JAVA has provided the following suggestiong to use identifiers in JAVA application:

1. It is suggestible to provide identifier with a particular meaning.
EX:
String aa = "abc123"; ---------> Not Suggestible
String accNo = "abc123"; ------> Suggestible

2. In Java Application, there is no length restriction for the identifiers, but, it is suggestible to manage length of the identifier around 10 symbols.
EX: 
String temporaryemployeeaddress = "Hyd"; -------> Not Suggestible
String tempEmpAddr = "Hyd"; --------------------> Suggestible

3. If we have multiple words with in a single identifier then it is suggestible to separate multiple words with special notation like '-' symbol.
EX:
String tempEmpAddr = "Hyd"; -----> Not Suggestible
String temp_Emp_Addr = "Hyd"; ---> Suggestible

You May Also Like --> Classes Vs Interference 

Datatypes: in oracle dbms

Datatypes:

------------------------------------------------------------------------------------------------------------------
1. Built-In Data Type:
Data type represents the type of data into a column based on data type, oracle engine allocates required memory for each value and the column.

A. String datatypes:

CHAR(size): to store fixed length char value.
   by default size is 1 char and Max size is 2000 char.

VARCHAR2(size): to store variable length char values & no minimum size, in this case, we                               must specify size.
Max size is 4000 char(upto 11g)
Max size is 32000 char(from 12c)

NCHAR(size): to store fixed length unicode character

NCHAR2(size): to store variable length unicode character.

LONG: it is similar to varchar2 datatype but max size is 2GB.

2. Numerical Data Type:
TO store Number type Data.

Number(precesion): it will store numeric values without decimal point. precesion represent                                       Max no of digit in the value.
Max value of precesion is 38 digits.

Number(precesion, scale): to store values with decimal point, scale represents max no of digits                               after decimal point.
                      EX: emp number(5)
                     prod_price(7,2)

3. Date Data Type:

Date: To store date type data.
Oracle system defined date format as
DD-MON-YY
DD- Date Digits
MON- First three char of month
YY - last 2 digits of year

Current_TimeStamp: to store date value, along with time format.
DD-MON-YY HH:MM:SS AM/PM

4. Binary Data Types:
Binary data type means unstructured data like images, digital signatures, thumb impressions, audio & video files.

RAW(size): max size 2000 bytes.
LONGRAW(size): max size 2GB.

5. LOB Data Types: (Large Objects)
to store large objects having more size then 2GB & max size is 4 GB.
CLOB: char LOB
BLOB: binary LOB
NCLOB: multi character LOB

6. ROWID: maintain physical address of each record.

7. Bfile: It is a pointer to a Binary File.

You may also like:
-->  Type Casting in JAVA
--> Data Type in JAVA

Thursday, December 29, 2016

Naming Rules: in oracle dbms

Naming Rules:

-----------------------------------------------

1. Each name should begun with alphabetic character.

2. Void character set is a-z, A-Z, 0-9, @, #, $, _ used but first name should be a letter.

3. Names are not case sensitive.

4. Spaces not allowed within the name.

5. Duplicate names are not allowed.

6. Reserved words not allowed as names.

7. Maximum length of a name is 30 character length.

EX:

 Valid   | Invalid
emp_dtls   | emp-dtls
emp123   | 123emp
pdod#info | prod.detls
table123   |      table
--------------------------

Wednesday, December 28, 2016

Identifiers in oracle

 Identifiers

--------------------------------------------------------------------------------------------------------
Identifier is a name provided to the programming elements like variables, methods, classes, interfaces.....

To provide identifiers in java program, java has provided the following rules & regulations.

A. Identifiers must not be started with a number, Identifiers may start with an alphabet, _ symbol, $          symbol but subsequent symbols may be a number, an alphabet, _ symbol, $ symbol.

EX:  String 9eid = "err";----------------> invalid
String eid = "err-1";---------------> valid
String emp9Id = "err891";---------------> valid
float $esal =   6932145f;---------------> valid
String _eaddr = "Hyd";---------------> valid
String emp_Name = "bali";---------------> valid
--------------

B. Identifiers are not allowing all operators & all special symbol except _ and $ symbol.
EX: 
 String emp.Name = "bali" ----------> invalid
String emp-Name = "bali" ----------> invalid
String emp_Name = "bali" ----------> valid
String emp$Name = "bali" ----------> valid
String emp+Name = "bali" ----------> invalid
String emp@Name = "bali" ----------> invalid
String _$_emp_$_$_Name = "bali" ----------> valid
---------------------------

C. Identifiers are not allowing spaces in the middle.
EX: 
  forName(--); ---------> Valid
for Name(--); ---------> invalid
getInputStream(-); ----> valid
get Input Stream (-); ------> Invalid
---------------------

D. Identifiers must not be duplicated within the same scope, identifiers may be duplicated in two             different scopes.
EX:
class A
{
int i = 10;
short i = 20;-------->error
boolean f = true;
void m1()
{
float f = 23.4f -----> no error
double f = 2850; -----> error
long i = 20; ---------> no error
System.out.println(i); ------> print local variable
System.out.println(this.i); -----> print class level variable
}
}

Note: Do you thinking why long i not giving any error, because it is already defined in class level variables?
And: for this you need to understand variables and memory storage, there are 3 type of memories in JAVA
1. Method Area   -----> it save static variable
2. Stack memory -----> saves local variables
3. Heap memory ------> saves non-static variables in form of objects.

so here in the given examples, int i and short i are state level non-static variable so they are saved in Heap memory while long i is saved in Stack memory, so when JVM search for long i, it is available in Stack memory and no other i variable available in stack memory so it causes no error while int i and short i, both are in same memory, so it causes error.
---------------------------------------------

E. In java application, we are able to use all predefined class names & interface names as identifiers.

EX: 1
int Exception= 10;
System.out.println(Exception);

Status: No compilation error
Output: 10

Note: Here Exception is an int variable.
---------------

EX: 2
String String = "String";
System.out.println(String);

Status: No compilation Error.
Output: String

Note: Here First String is as String class, 2nd String as a variable, 3rd String as value of variable.
--------------

EX: 3
int System = 10;
System.out.println(System);

Status: Compilation Error.
Reason: In java application , if we declare "System" as an integer variable then in the remaining program, we must use that System as integer variable only, we must not use that System as original class name, if we use "System" as original class name then compiler will rise an error.

In the above context if wi want to use System as class name, then we have to use its "fully qualified name" providing class name along their package name is called as "Fully qualified name".

EX:
class Test
{
public static void main(String[] args)
{
int System = 10;
java.lang.System.out.println(System);
System=System + 10;
java.lang.System.out.println(System);
}
}

Status: No compilation error
Output:
10
20
---------------------------

Along with the above rules & regulations, JAVA has provided the following suggestiong to use identifiers in JAVA application:

1. It is suggestible to provide identifier with a particular meaning.
EX:
String aa = "abc123"; ---------> Not Suggestible
String accNo = "abc123"; ------> Suggestible

2. In Java Application, there is no length restriction for the identifiers, but, it is suggestible to manage length of the identifier around 10 symbols.
EX: 
String temporaryemployeeaddress = "Hyd"; -------> Not Suggestible
String tempEmpAddr = "Hyd"; --------------------> Suggestible

3. If we have multiple words with in a single identifier then it is suggestible to separate multiple words with special notation like '-' symbol.
EX:
String tempEmpAddr = "Hyd"; -----> Not Suggestible
String temp_Emp_Addr = "Hyd"; ---> Suggestible


Tokens in language fundamentals in oracle dbms

1. Tokens: 

Any logical unit in java programming is called as Lexeme.

The collection of Lexeme come under a particular group called as "Tokens".
Lexeme and tokens



Q. Find the no of lexemes & tokens in following expression?
int a = b + c *d;

Ans: int,a,=,b,=,+,*,d,; --------> 9 lexeme
int ----------------> data type
a,b,c,d ------------> Variables
=,+,* --------------> operator
; ------------------> special symbol/ terminator

Tokens ---------------> 4 types of token.
------------------------------------------------------------------------------------------

To prepare java application, java has provided the following tokens:
1. Identifiers
2. Literals
3. Keywords/reserved words
4. operators

1. Identifiers:

-------------------
Identifier is a name provided to the programming elements like variables, methods, classes, interfaces.....

To provide identifiers in java program, java has provided the following rules & regulations.

A. Identifiers must not be started with a number, Identifiers may start with an alphabet, _ symbol, $          symbol but subsequent symbols may be a number, an alphabet, _ symbol, $ symbol.

EX: String 9eid = "err";----------------> invalid
String eid = "err-1";---------------> valid
String emp9Id = "err891";---------------> valid
float $esal =   6932145f;---------------> valid
String _eaddr = "Hyd";---------------> valid
String emp_Name = "bali";---------------> valid
--------------

B. Identifiers are not allowing all operators & all special symbol except _ and $ symbol.
EX: String emp.Name = "bali" ----------> invalid
String emp-Name = "bali" ----------> invalid
String emp_Name = "bali" ----------> valid
String emp$Name = "bali" ----------> valid
String emp+Name = "bali" ----------> invalid
String emp@Name = "bali" ----------> invalid
String _$_emp_$_$_Name = "bali" ----------> valid
---------------------------

C. Identifiers are not allowing spaces in the middle.
EX: forName(--); ---------> Valid
for Name(--); ---------> invalid
getInputStream(-); ----> valid
get Input Stream (-); ------> Invalid
---------------------

D. Identifiers must not be duplicated within the same scope, identifiers may be duplicated in two             different scopes.
EX:
class A
{
int i = 10;
short i = 20;-------->error
boolean f = true;
void m1()
{
float f = 23.4f -----> no error
double f = 2850; -----> error
long i = 20; ---------> no error
System.out.println(i); ------> print local variable
System.out.println(this.i); -----> print class level variable
}
}

Java Language Fundamentals

Language Fundamentals:

----------------------------------------------------------------------------------------------------------------
Java has provided the following language fundamentals to prepare applications:

1. Tokens
2. Data Type
3. Type Casting
4. Java Statement
5. Arrays

NOTE: The descriptions of all the fundamentals are in following posts, i also attached the links of the corresponding post with the fundamental name, you can directly click on name and go on that post.


You may also like: ---->  Difference between & and &&

SQL Commands: ORACLE

SQL Commands:

1. DDL Commands (data definition language)
A. CREATE
B. TRUNCATE
C. ALTER
D. RENAME
E. DROP

2. DML Commands (Data Manipulation language)
A. INSERT
B. UPDATE
C. DELETE

3. DCL Commands (Data control language)
A. GRANT
B. REVOKE

4. TCL commands (Transaction control language)
A. COMMIT
B. ROLLABCK
C. SAVEPOINT

5. DRL command (Data Retrieval language)
A. SELECT

Note: all commands except select are physical command means they effect database,
select is a logical command and it not affect database.

Monday, December 26, 2016

Oracle version

Version of Oracle:


In 1986, oracle Corp released its first commercial database i.e. oracle 7
Oracle-7: It is a stand alone RDBMS, it is not supporting online processing.

Oracle-8: It is stand alone RDBMS and it having indexes.
Note: these 2 database are unable to process business data in online process.

Oracle-8i: it is supporting internet application like webpages(html & java) supports online data processing.
   i stands for internet application from this version oracle supporting online data processing.

Oracle-9i: It also supporting Internet application
   it Support online data processing.
   It supports e-buz development tools(ERP-Enterprises resources planet)

Oracle-10g: (grid technology)
   a grid is nothing but a mesh like architecture.
   each consecutive point in the mesh, is considered as server.
   each server connected with atleast one server within the grid.
-  g for grid technology, within database grid, any server is easily communicating with any other server. i.i. supporting centralized
data processing.

Oracle-11g: It is having in built data warehouse builder.
    It is having OLTP development tools & OLAP development tools-(Oracle Warehouse Builder)

Oracle-12c: Cloud Computing
    It provides a facility to connect with any technology cloud without installing technology in the personal system.

Oracle

Oracle:

It is an RDBMS from oracle corporation.
Any RDBMS is used to store and process Business Data.

Database Concept:

------------------------------
1. Data : Collection of Information of one entity is known an Data
ex: any one employee data, any one product data etc

2. Database: collection of Information of all objects with in the business, technically a database is a software to automate business activities.

3. DBMS(database management system): a database, which is providing management system services like:
A. Entity new data or inserting new data.
B. Updating data
C. Deleting unwanted data
D. Authentication or authenticating user
E. Providing security

4. RDBMS(relational database management System): It is a collection of inter-related data of all inter related objects within the business.
Note:
A. generally data is generated from each business object & business transaction.
B. as a database developer, we need to develop database application program(Stored procedures, functions, packages & triggers). each database application program is responsible for at least one business activity.

How to install java part-4

6. Execute JAVA program:

------------------------------------------------------------------------------------------------------------
To execute java program, we have to use the following command or command prompt at the location where main class .class file is existed.
Java Main_Class_Name

EX: D:\java10>java FirstApp

If we provide the above command on command prompt then operating system will identify “java” command at “C:\java\jdk1.7.0_79\bin”, through path environment variable, JVM will execute “java” command, with this, JVM Software will be activated and JVM will perform the following actions:

A. JVM will take main class name from command prompt.
B. JVM will search for main class .class file at 3 locations:
i. current location,
ii. at java predefined library and
iii. at the location referred by “class path” environment variable.
C. If the required main class .class file is not identified at all the above locations then JVM will provide the following:

JAVA6: java.lang.NoClassDefFoundError: FirstApp
JAVA7: Error: Could not find or local main class: FirstApp

Note: if the required main class .class file is available at another location then to make available that .class file to JVM, we have to set “class path” environment variable.
D:\java10>set classpath = E:\abc;

D. If the required main class .class file is available at either of the above locations them JVM will load main class byte code to the memory.
E. After loading main class byte code to the memory, JVM will search for main() method at main class.
F. If the required main () method is not available then JVM will provide the following Exceptions.

JAVA6: java.lang.NoSuchMethodError: main
JAVA7: Error: Main method not found in class FirstApp, please defined the main method as:
            public static void main(String[] args)

G. If the required main() method is existed in main class the JVM will execute main() method by creating a thread called as “main thread”.

H. When Main thread reached to the ending point of main() method, Main thread will come Dead State, with this, JVM will terminate all of its internal processes and JVM will go to shutdown mode.

Saturday, December 24, 2016

How to Install JAVA part-3

5. Compile JAVA file:

--------------------------------------------------------------------------------------------------------------------
The main Intention to compile JAVA files is:

A. To translate JAVA code from high level representation to low level representation.
B. To check developers mistake in JAVA application

To compile JAVA files, we have to use the following command on command prompt:

Javac File_Name.java

EX: D:\java10>javac FirstApp.java
---------------------------------------------

C. If we provide the above command on command prompt then operating system will perform the following actions:
i. Operating System will take “javac” command prompt
ii. Operating System will search for javac command at its predefined command list and at  the location refereed by “path” environment variable.
iii. If “javac” is not identified at both the location then operating system will display the following message.
iv. ‘javac’ is not recognized as an internal or external command, operable program or batch file.

Note: To give all java commands location information to the operating system, we have to set “path” environment variable to “C:\java\jdk1.7.0_79\bin;
On command Prompt:

D:\Java10>set path=C:\java\jdk1.7.0_79\bin;

D. If javac is identified by the operating system at either of the above location then operating system will execute “javac” command, with this, JAVA compiler software will be activated and JAVA compiler will perform the following actions.
 I.     Compiler will take the provided JAVA file from command prompt.
II.     Compiler will check whether the specified JAVA file is existed or not at current location
III.    If the specified JAVA file is not existed then compiler will provide the following message :   

         javac: file not Found: FirstApp.java
run java through command prompt
File not found in JAVA


IV.     If the specified in the JAVA file then the compiler will display error message on command  prompt.
V.     If no error is identified in the present JAVA file then the compiler will generate .class files.

Note: Generating Number of .class files is not at all depending on the no. of .java files which we compiled, it is completely depending on the no. of classes, abstract classes, interfaces, enums and inner classes which we used In present JAVA file.

If we want to compile JAVA file from current location & if we want to select generated .class file to a particular target file then we have to use ‘-d’ option.
EX: D:\java10\javac –d C:\abc FirstApp.java

If we want to compile JAVA file from current location and if we want to generate .class files by creating folder, structure with respect to the package name then we have to use ‘-d’ option along with “javac” command.

EX: File Name: D:\java10\FirstApp.java
enum E
{          
}
interface I
{
}
abstract class A{
           
}
class B {
            class C{
                       
            }
}
class FirstApp {
            public static void main(String[] args){
                        System.out.println("First JAVA Application");
            }
}

On command Prompt:
D:\java10>javac –d C:\abc FirstApp.java
compilation process of a java file
Compilation Format of JAVA File


If we want to compile all JAVA files which are existed at current location then we have to use the following command on command Prompt.
 D:\java10>javac *.java

If we want to compile all JAVA files which started with a common prefix then we have to use the following command on command prompt:
D:\java10>javac student*.java

If we want to compile all JAVA files which are having a common postfix then we have to use the following command on command prompt:
D:\java10>javac *Emails.java

If we want to compile all java files which contains a common word then we have to use the following command on command prompt:

D:\java10>javac *Account*.java

How to Install JAVA Part-2

4. Save JAVA File:

---------------------------------------------------------------------------------------------------------------
To save JAVA File, we have to use following conditions:

A. If the present java file contains any public element [class, interface, abstract class, enum] then the present JAVA file must be saved with public element name only, if we violate this condition then compiler will rise an error.

B. If no pubic element is existed in present JAVA file then it is possible to save JAVA file with any name like abc.java or xyz.java, but it is suggestible to save JAVA file with main class name instead of any other name.

EX: File Name: abc.java
--------------------------------
class FirstApp {
            public static void main(String[] args) {
                        System.out.println(“First JAVA Application”);
            }
}
Status: No compilation error, but not suggestible to save abc.java


EX: File Name: FirstApp.java
class FirstApp {
            public static void main(String[] args){
                        System.out.println("First JAVA Application");
            }
}
Status: No compilation Error & Suggestible.


EX: File Name: FirstApp.java
public class A {
}
class FirstApp {
            public static void main(String[] args){
                        System.out.println("First JAVA Application");
            }
}
Status: Compilation Error


EX: File Name: A.java
public class A {
}
class FirstApp {
            public static void main(String[] args){
                        System.out.println("First JAVA Application");
            }
}

Status: No Compilation Error.

Q. Is it possible to provide more than one public class with in a single java file?
ANS. No, it is not possible to provide more than one public class with in a single JAVA file, because, if we provide more than  one public class with in a single JAVA file, then we must save that java file with more than one name, which is not possible in OS.

EX: File Name: A.java
public class A {
}
public class B {
}
class FirstApp {
            public static void main(String[] args){
                        System.out.println("First JAVA Application");
            }
}
Status: compilation Error.


Friday, December 23, 2016

JAVA Interview Question

Q. 41
11. class Alpha {
12. public void foo() { System.out.print(“Afoo”); }
13. }
14. public class Beta extends Alpha {
15. public void foo() { System.out.print(“Bfoo”); }
16. public static void main(String[] args) {
17. Alpha a = new Beta();
18. Beta b = (Beta)a;
19. a.foo();  20. b.foo();
21. }
22. }
What is the result?
A. Afoo Afoo
B. Afoo Bfoo
C. Bfoo Afoo
D. Bfoo Bfoo
E. Compilation fails.
F. An exception is thrown at runtime.

Q. 42 Given:
7. void waitForSignal() {
8. Object obj = new Object();
9. synchronized(Thread.currentThreat()) {
10. obj.wait();
11. obj.notify();
12. }
13. }
Which statement is true?
A. This code may throw an interruptedException.
B. This code may throw an illegalstateException.
C. This code may throw a TimeoutException after ten minutes.
D. This code will not compile unless “obj.wait()” is replaced with “((Thread) obj).wait()”.
E. Reversing the order of obj.wait() and obj.notify() may cause this method to complete normally.
F. A call to notify() or notifyAll() from another thread may cause this method to complete normally.

Q, 43 Given:
1. public class TestSeven extends Thread {
2. private static int x;
3. public synchronized void doThings() {
4. int current = x;
5. current++;
6. x = current;
7. }
8. public void run() {
9. doThings();
10. }
11. }
Which statement is true?
A. Compilation fails.
B. An exception is thrown at runtime.
C. Synchronizing the run() method would make the class thread-safe.
D. The data in variable “x” are protected from concurrent access problems.
E. Declaring the doThings() method as static would make the class thread-safe.
F. Wrapping the statements within doThings() in a synchronized (new Object()) { } block would make the class thread-safe.

Q. 44 Given:
11. public void testIfA() {
12. if (testlfB(“True”)) {
13. System.out.println(“True”);
14. } else {
15. System.out.println(“Not True”);
16. }
17. }
18. public Boolean testlfB(String str) {
19. return Boolean.valueof(str);
20. }
What is the result when method testlfA is invoked?
A. True
B. Not True
C. An exception is thrown at runtime.
D. Compilation fails because of an error at line 12
E. Compilation fails because of an error at line 13.

Q.45 when comparing java.io.BufferedWriter to java.io.FileWriter, which capability exists as a method in only one of the two?
A. closing the stream.
B. flushing the stream
C. writing to the Stream
D. marking a location in the stream
E. writing a line separator to the stream

46. The calendar for the year 2007 will be the same for the year.
A. 2014 B. 2016 c. 2017                  D. 2018

47. A man standing at a point P is watching the top of a tower, which makes an angle of elevation of 30 degree with the man’s eye. The man walks some distance towards the tower to watch its top and the angle of the elevation becomes 60 degree. What is the distance between the base of the tower and the point P?
A. 43 units           B. 8 units             C. 12 units           D. Data inadequate.

48. Two ships are sailing in the sea on the two sides of a lighthouse. The angle of elevation of the top of the lighthouse is observed from the ships are 30 degree and 45 degree respectively. If the lighthouse is 100 m high, the distance between the two ships is:
A. 173 m               B. 200 m               C. 273 m               D. 300 m

49. A and B take part in 100 m race. A runs at 5 kmph. A gives B a start of 8 m and still beats him by 8 seconds. The speed of B is:
A. 5.15 kmph      B. 4.14 kmph      C. 4.25 kmph      D. 4.4 kmph

50. In 100 m race, A covers the distance in 36 seconds and B in 45 seconds. In this race A beats B by:

A. 20 m                 B. 25m                  C. 22.5m               D. 9 m

Exception

 Exception

--------------------------------------------------------------------------------------------------------------

Exception is an unexpected event occurred at RUN-TIME provided by the users while entering Dynamic Input, provided by Database Engine while Executing SQL queries in JDBC application, provided by the network while establish connection between local machine and remote machine in
Distributed application.... cause abnormal termination to the application.

In java, there are two types of terminations...
1. Smooth termination
2. abnormal termination

If a program is termination at end of the program, then the termination is called as "Smooth Termination".

If a program is terminated at middle of the program then the termination is called as "Abnormal Termination".

In JAVA application, Abnormal termination may crash to local operating system, it may provide hanged out situation to the network application problem.

To overcome the above problems, we have to handle exceptions properly for this, we have to use a set of mechanisms explicitly called as
"Exception Handling Mechanisms".

JAVA is a Robust Programming language because:
1. JAVA is having very good memory management system in the form of HEAP memory management system, a dynamic memory management System,
it allocates and deallocates memory for the objects at RUNTIME.

2. JAVA is having very good Exception handling mechanism becaue JAVA has provided very good predefined library to represent and handle
almost all the exception which are generated frequetly.

There are two types of Exception in JAVA...
1. Predefined Exception
2. User Defined Exception

1. Predefined Exception :

-------------------------------
These exception are provided by JAVA programming language along with java predefined library.

There are two types of predefined exceptions..
1. Checked Exception
2. Unchecked Exception

Q. What is the difference between pure checked exception and partially checked exception?
----------------------------------------------------------------------------------------------------
Ans. Checked Exception are the exception recognized by the compiler (not occured at compile time) at compilation time.

Unchecked Exception are the exceptions recognized and occured at RUNTIME.
EX: Runtime Exception and its sub classes, Error and its sub classes are the examples for Unchecked Exception and all the remaining exception
classes in the above diaram are examples for checked exception.
---------------------------------------------------------------------------------------------------------

There are two Types of Checked Exceptions:
1. Pure Checked Exception
2. Partially Checked Exception

Q. what is the difference between pure checked exception and partially checked exception?
Ans. if any checked exception contains only checked exception as sub classes then that checked exception is called as Pure Checked Exception.
EX: IOException

If any checked exception contains at least one unchecked exception as subclass then that checked exception is called as Partially Checked Exception.
EX: Excepiton, Throwable

Error Vs Exception in JAVA

Q. what is the difference between Error and Exception?

Ans.
1. Error is a problem in JAVA application, it may affect compilation and execution of the JAVA program.

There are two types of Errors in JAVA Application...
1. compile time Error
2. Runtime Errors

1. Compile Time Errors:
----------------------------------
Compile time error is a problem identified at compile time.

In general , there are three basic errors in all the programming language
a. Lexical Error: Mistake in keywords
EX: int i = 10; ------> valid
        nit i = 10; ------> invalid

b. Syntax Error: Grammatical Mistakes
EX: int i = 10; ---> valid
   int i = 10 ------> invalid
   i 10 int; --------> invalid

c. semantic error: operation with incompatible types
Ex: int i = 10; ---> valid
   boolean b = true;
   float = i + b;

2. Run Time Error:
These are the problems occurred at run time, for which, we are unable to provide programmatic           solution.
EX: InSufficientMainMemoryErrors
NoClassDefFoundError
NoSuchMethodError
JVMInternalProblemError

2. Exception:
------------------
These are problems for which, we are able to provide programmatic solutions:
EX:
1. ArithmeticException
2. NullPointerException
3. ArrayIndexOutOfBoundsException
---------------------------------------------------------------------------------------

Thursday, December 22, 2016

JAVA Interview Question 31-40

Q: 31 Given:
15. public class Yippee {
16. public static void main(String[] args) {
17. for (int x = 1; x < args.length; x++) {
18. System.out.print(args[x] + “ “);
19. }
20. }
21. }
and two separate command line invocations:
java Yippee
java Yippee 1 2 3 4

What is the result?
A. No output is produced.
1 2 3
B. No output is produced.
2 3 4
C. No output is produced.
1 2 3 4
D. An exception is thrown at runtime.
1 2 3
E. An exception is thrown at runtime.
2 3 4
F. An exception is thrown at runtime.
1 2 3 4

Q. 32 Given:

10. class Nav{
11. public enum Direction {NORTH, SOUTH, EAST, WEST}
12. }
13. public class Sprite {
14. // insert code here
15. }

Which code, inserted at line 14, allows the Sprite class to compile?
A. Direction d = NORTH;
B. Nav. Direction d = NORTH;
C. Direction d = Direction.NORTH;
D. Nav.Direction d = Nav.Direction.NORTH;

Q: 33 Given:
11. public class Ball{
12. public enum Color {RED, GREEN, BLUE};
13. public void fool(){
14. // insert code here
15. { System.out.println(c);}
16. }
17. }
Which code inserted at line 14 causes the foo method to print RED, GREEN, and BLUE?
A. for(Color c : Color.values() }
B. for(Color c = RED; c <= BLUE; c++)
C. for(Color c; c.hasNext(); c.next() )
D. for(Color c = Color[0]; c <= Color[2]; c++)
E. for(Color C = Color.RED; c <= Color.BLUE; c++)

Q. 34 Given:
3. public class Spock{
4. public static void main(String[] args){
5. Long tail = 2000L
6. Long distance = 1999L
7. Long story = 1000L
8. if((tail > distance) ^ ((story * 2) == tail))
9. System.out.print(“1”);
10. if((distance + 1 != tail) ^ ((story * 2) == distance))
11. System.out.print(“2”) ;
12. }
13. }
What is the result?
A. 1
B. 2
C. 12
D. Compilation fails.
E. No output is produced.
F. An exception is thrown at runtime.

Q. 35 Given:
25. int x = 12;
26. while (x<10) {
27. x--;
28. }
29. System.out.print(x);
What is the result?
A. 0
B. 10
C. 12
D. Line 29 will never be reached.

Q. 36 Given:
11. static void test() throws Error {
12. if (true) throw new AssertionError ();
13. System.out.print(“test”);
14. }
15. public static void main(String[] args) {
16. try(test); }
17. catch (Exception ex} {System.out.print(“exception”); }
18. System.out.print(“end”);
19. }
What is the result?
A. end
B. Compilation fails.
C. exception end.
D. exception test end
E. A Throwable is thrown by main.
F. An Exception is thrown by main.

Q. 37 Given:
33. try {
34. // some cade here
35. } catch (NullPointerException e1) {
36. System.out.print(“a”);
37. } catch (RuntimeException e2) {
38. System.out.print(“b”);
39. } finally {
40. System.out.print(“c”);
41. }
What is the result if a NullPointerException occurs on line 34?
A. c
B. a
C. ab
D. ac
E. bc
F. abc

Q. 38
Click the Exhibit Button.
1. public class Test {
2.
3. public static void main( String[] args) {
4. Boolean assert = true;
5. if(assert) {
6. System.out.println(“assert is true”);
7. }
8. }
9.
10. }
Given:
Javac –source 1.3 Test.java

What is the result?
A. Compilation fails.
B. Compilatin Succeeds with errors.
C. Compilation succeeds with warnings.
D. Compilation succeeds without warnings or errors.

Q. 39 Given:
11. public void genNumbers() {
12. ArrayList numbers = new ArrayList();
13. for (int i=0; I<10; i++) {
14. int value = i * ((int) Math.random());
15. integer intObj = new Integer(Value);
16. numbers.add(intObj);
17. }
18. System.out.println(numbers);
19. }

Which line of code marks the earliest point that an object referenced by intObj becomes a candidate for garbage collection?
A. Line 16
B. Line 17
C. Line 18
D. Line 19
E. The object is NOT a candidate for garbage collection.

Q. 40 Given:
1. class SuperClass {
2. public A getA(){
3. return new A();
4. }
5. }
6. class SubClass extends SuperClass {
7. public B getA() {
8. return new B();
9. }
10. }
Which statement is true?
A. Compilation will succeed if A extends B.
B. Compilation will succeed if B extends A.
C. Compilation will always fail because of an error in line 7
D. Compilation will always fail because of an error in line 8