Hide Answers
1.what is a transient variable?
2.which containers use a border Layout as their default layout?
3.Why do threads block on I/O?
4. How are Observer and Observable used?
5. What is synchronization and why is it important?
6. Can a lock be acquired on a class?
7. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
8. Is null a keyword?
9. What is the preferred size of a component?
10. What method is used to specify a container's layout?
11. Which containers use a FlowLayout as their default layout?
12. What state does a thread enter when it terminates its processing?
13. What is the Collections API?
14. Which characters may be used as the second character of an identifier, but not as the first character of an identifier?
15. What is the List interface?
16. How does Java handle integer overflow and underflow?
17. What is the Vector class?
18. What modifiers may be used with an inner class that is a member of an outer class?
19. What is an Iterator interface?
20. What is the difference between the >> and >>> operators?
21. Which method of the Component class is used to set the position and size of a component?
22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
23.What is the difference between yielding and sleeping?
24. Which java.util classes and interfaces support event handling?
25. Is sizeof a keyword?
26. What are wrapped classes?
27. Does garbage collection guarantee that a program will not run out of memory?
28. What restrictions are placed on the location of a package statement within a source code file?
29. Can an object's finalize() method be invoked while it is reachable?
30. What is the immediate superclass of the Applet class?
31. What is the difference between preemptive scheduling and time slicing?
32. Name three Component subclasses that support painting.
33. What value does readLine() return when it has reached the end of a file?
35. What is clipping?
36. What is a native method?
37. Can a for statement loop indefinitely?
38. What are order of precedence and associativity, and how are they used?
39. When a thread blocks on I/O, what state does it enter?
40. To what value is a variable of the String type automatically initialized?
41. What is the catch or declare rule for method declarations?
42. What is the difference between a MenuItem and a CheckboxMenuItem?
43. What is a task's priority and how is it used in scheduling?
44. What class is the top of the AWT event hierarchy?
45. When a thread is created and started, what is its initial state?
46. Can an anonymous class be declared as implementing an interface and extending a class?
47. What is the range of the short type?
48. What is the range of the char type?
49. In which package are most of the AWT events that support the event-delegation model defined?
50. What is the immediate superclass of Menu?
Hide Answers
Sunday, October 28, 2018
Wrapper class in java - example
f the main advantages of wrapper class is avoiding explicit type casting for primitive types while using collections.
Here is a basic example which will give compilation errors without explicit casting as shown below.
You can correct the program by adding type casting and here is a working sample
To avoid this explicit casting wrapper, we can add wrapper class as a generic argument to the collection.
eg: List<Integer> intList = new ArrayList<Integer>();
With this declaration of wrapper class, you can avoid explicit type casting. This example might not make good sense as we are declaring the list ourselves but when we are working with numerous lists in a big project, you can find lot of instances where avoiding explicit type casting is very useful and using wrapper classes save us from type casting exceptions.
One more advantage is - as you are declaring Integer wrapper class as a generic argument, while coding adding any other wrapper class value to the list will give you a compilation error.
Another useful feature used with wrapper classes is unboxing.
int value= intList.get(0); // here hava compiler will unbox Integer wrapper class value to int premitive type
Here is a basic example which will give compilation errors without explicit casting as shown below.
You can correct the program by adding type casting and here is a working sample
public class WrapperClassInJava {
public static void main(String[] args) {
List intList = new ArrayList();
intList.add(123);
int value= (int)intList.get(0);
}
}
To avoid this explicit casting wrapper, we can add wrapper class as a generic argument to the collection.
eg: List<Integer> intList = new ArrayList<Integer>();
With this declaration of wrapper class, you can avoid explicit type casting. This example might not make good sense as we are declaring the list ourselves but when we are working with numerous lists in a big project, you can find lot of instances where avoiding explicit type casting is very useful and using wrapper classes save us from type casting exceptions.
public class WrapperClassInJava {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
intList.add(123);
int value= intList.get(0);
System.out.println(value);
}
}
One more advantage is - as you are declaring Integer wrapper class as a generic argument, while coding adding any other wrapper class value to the list will give you a compilation error.
Another useful feature used with wrapper classes is unboxing.
int value= intList.get(0); // here hava compiler will unbox Integer wrapper class value to int premitive type
Difference between C and Java
Difference between .exe and .class
.exe file contains machine language instructions for the microprocessor. It is system dependent. .class file contains byte code instructions for JVM. It is system independent.
Difference between #include and import statements
#include makes the compiler to copy the header file code into the C program so the program size will increase thus it wastes memory and processor time. Import statement makes JVM to go a package, execute the code and then substitute the result in a java program. So no code is copied. Import is more efficient than include. JRE = JVM + Java LibraryOther Major Differences inlude
1. C breaks down to functions while JAVA breaks down to Objects. C is more procedure-oriented while JAVA is data-oriented.
2. Java is an Interpreted language while C is a compiled language.
3. C is a low-level language(difficult interpretation for the user, closer significance to the machine-level code) while JAVA is a high-level lagunage(abstracted from the machine-level details, closer significance to the program itself).
4. C uses the top-down {sharp & smooth} approach while JAVA uses the bottom-up {on the rocks} approach.
5. Pointer go backstage in JAVA while C requires explicit handling of pointers.
6. The Behind-the-scenes Memory Management with JAVA & The User-Based Memory Management in C.
7. JAVA supports Method Overloading while C does not support overloading at all.
8. Unlike C, JAVA does not support Preprocessors, & does not really them.
9. The standard Input & Output Functions. Although this difference might not hold any conceptual(intuitive) significance, but it’s maybe just the tradition. C uses the printf & scanf functions as its standard input & output while JAVA uses the System.out.print & System.in.read functions.
10. Exception Handling in JAVA And the errors & crashes in C. When an error occurs in a Java program it results in an exception being thrown. It can then be handled using various exception handling techniques. While in C, if there’s an error, there IS an error.
Java Data Types
Data Types & Literals in Java
A data type represents the type of data we are storing into variables. The value we are storing in the variable is known as literal.
Integer:
Represent integer numbers. Integer numbers are numbers without fractional part.
Data Type
|
Memory Size
|
Min & Max
values
|
Byte
|
1 byte
|
-128 to +127
|
Short
|
2 bytes
|
-32768 to +32767
|
Int
|
4 bytes
|
-2147483648 to +2147483647
|
long
|
8 bytes
|
-9223372036854775808 to
+9223372036854775807
|
Float data type:
Float data type represents floating point numbers. Float data types are used to
handle numbers with decimal points.
Data Type
|
Memory Size
|
Min & Max
values
|
float
|
4 bytes
|
-3.4e38 to +3.4e38
|
Double
|
8 bytes
|
-1.7e308 to +1.7e308
|
Example:
float pi = 3.14F; (by adding F JVM allocates 4 bytes otherwise JVM allocates 8 bytes.)
double distance = 1.98e8;
Difference between float and double?
float represents up to 7 digits accurately after decimal point. (single precision floating point)
double represents up to 15 digits accurately after decimal point. (double precision floating point)
Character data type:
Character data type represents a single character.
Data Type
|
Memory Size
|
Min & Max
values
|
char
|
2 bytes
|
0 to 65535
|
Example:
char ch = 'x';
What is Unicode?
Unicode is a specification to include the alphabets of international languages into
character set of java. Unicode system uses 2 bytes to represent a character.
String data type:
String data type represents a group of characters. String is also a class and We will descuss more about it in the coming lessions.
Example:
String name = "Java";
String str = new String("Java");
Boolean data type:
Boolean data type represents either true or false.
Example:
boolean response = false;
Converting a string to java primitive types
How to convert a String to int, to float, to double and to long.
This article is going to address converting a String to primitive data types with examples.
public class ConvrtingStringToPrimitives {
public static void main(String[] args) {
int intNumber = convertStringInt("123");
System.out.println("intNumber:\t"+intNumber);
long longNumber = convertStringLong("123456");
System.out.println("longNumber:\t"+longNumber);
double doubleNumber = convertStringDouble("232.12");
System.out.println("doubleNumber:\t"+doubleNumber);
float floatNumber = convertStringFloat("2223.232");
System.out.println("floatNumber:\t"+floatNumber);
}
/**
* @param intInput
* @return int
*/
private static int convertStringInt(String intInput){
return Integer.parseInt(intInput);
}
/**
* @param longInput
* @return long
*/
private static long convertStringLong(String longInput){
return Long.parseLong(longInput);
}
/**
* @param doubleInput
* @return double
*/
private static double convertStringDouble(String doubleInput){
return Double.parseDouble(doubleInput);
}
/**
* @param floatInput
* @return float
*/
private static float convertStringFloat(String floatInput) {
return Float.parseFloat(floatInput);
}
}
Output:
intNumber: 123
longNumber: 123456
doubleNumber: 232.12
floatNumber: 2223.232
Java Comments
Comments represent the text to describe the aim and features of a program.
Comments increase the readability of the program.
There are 3 types of comments in Java.
- Single line comment (//text)
- Multi-line comment (/* text */)
- Java documentation comments (/** text */)
These documents are useful to create a .html file called API document from a java
program.
API Document:
Is a .html file that contains description of all the features of a software or a technology
or a product. It is similar to help file.
To create API document, we use javdoc compiler.
How to check date older than an year? [in Java]
The following java program will check for a date older than 365 days.
public class CheckDateOlderThan365Days {
public static void main(String[] args) {
String givenDateStr = "12/20/2014";
Date givenDate = new Date(givenDateStr);
Date oldDate = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(oldDate);
cal.add(Calendar.DAY_OF_MONTH, -365);
oldDate = cal.getTime();
boolean isDateOlder = givenDate.before(oldDate);
if(isDateOlder){
System.out.printf("Given date %s is older than 365 days",givenDate);
} else {
System.out.printf("Given date %s is newer than 365 days",givenDate);
}
}
}
Output:Given date Sat Dec 20 00:00:00 EST 2014 is older than 365 days
Change java home and java path in windows 7 or windows 8
Changing the Java Home and path is little different in Windows 7 and Windows 8. Please follow the below steps to change the version of Java to Java 8 in Windows 7 or Windows 8.
First check your java version in command prompt using 'java -version' command.
Go to system folder "C:\ProgramData\Oracle\Java\javapath". You will see 3 java exe files as shows below.
By checking the properties you can confirm the current version of Java.
Delete all 3 files in the folder.
Now Go to your installed JDK's bin folder - in my case it is C:\Program Files\Java\jdk1.8.0_25\bin and copy the same files i.e java.exe, javaw.exe and javaws.exe.
Paste all 3 files in "C:\ProgramData\Oracle\Java\javapath"
Now open command prompt to check the version of Java - command is 'java -version' and you can see that the version is changed to jdk1.8.0_25
You can check Install java in wondows if you don't have a Java version installed in Windows.
First check your java version in command prompt using 'java -version' command.
Go to system folder "C:\ProgramData\Oracle\Java\javapath". You will see 3 java exe files as shows below.
By checking the properties you can confirm the current version of Java.
Delete all 3 files in the folder.
Now Go to your installed JDK's bin folder - in my case it is C:\Program Files\Java\jdk1.8.0_25\bin and copy the same files i.e java.exe, javaw.exe and javaws.exe.
Paste all 3 files in "C:\ProgramData\Oracle\Java\javapath"
Now open command prompt to check the version of Java - command is 'java -version' and you can see that the version is changed to jdk1.8.0_25
You can check Install java in wondows if you don't have a Java version installed in Windows.
Abstraction in java
What is abstraction?
The basic abstraction in Java is a class. A class can be used to hide certain implementation details and only show the essential features of the object. Abstraction focuses on the observable behavior of an object.A class models an abstraction by defining the properties and behaviors for the objects representing the abstraction. An object exhibits the properties and behaviors defined by its class.
class Employee {
private int employeeId;
private String employeeName;
public int getEmployeeId(){
return this.employeeId;
}
}
Here Employee is an abstraction and it models an abstraction by defining employee details like employeeId and employeeName. Methods inside Employee like getEmployeeId() define the behavior of abstraction.
To the user(most probably another class) who is using Employee object to get an employee Id, the implementation details are hidden.
eg: Imagine a media player. It abstracts the concepts of playing, pausing, fast-forwarding, etc. As a user, you can use this to operate the device.
"One point of confusion regarding abstraction is its use as both process and an entity. Abstraction, as a process, denotes the extracting of the essential details about an item, or a group of items, while ignoring the inessential details. Abstraction, as an entity, denotes a model, a view, or some other focused representation for an actual item."
I found lot of articles in internet confusing the readers with the concept of abstract class with abstraction and with my experience of Java programming - these two are different concepts.
abstract classes and interfaces are used to implement inheritance and class is a basic abstraction in Java.
How to parse JSON in Java - Marshalling to Java Objects
Often times there will be a need to marshal JSON data to Java objects to store them in a data source. I have explained the concept using simple Java programs - I have used GSON library to do this and this will be pretty much same using any other libraries.
import com.google.gson.Gson;
public class JavaJsonSerializer {
public static void main(String[] args) {
/*
* {
"pageInfo": {
"pageName": "TheTestbook",
"pagePic": "content.jpg"
},
"posts": [{
"postId": "123456",
"postName": "Java Post"
}]
}
*/
String jsonString = "{ \"pageInfo\": { \"pageName\": \"TheTestbook\",
\"pagePic\": \"content.jpg\" },"
+ " \"posts\": [{ \"postId\": \"123456\",
\"postName\": \"Java Post\" }]}";
Gson gson = new Gson();
BlogPost blogPost = gson.fromJson(jsonString, BlogPost.class);
System.out.println(blogPost);
}
}
To support this Main program - you have to create 3 more Java classes
public class BlogPost {
private PageInfo pageInfo;
private List posts;
public PageInfo getPageInfo() {
return pageInfo;
}
public void setPageInfo(PageInfo pageInfo) {
this.pageInfo = pageInfo;
}
public List getPosts() {
return posts;
}
public void setPosts(List posts) {
this.posts = posts;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BlogPost [pageInfo=");
builder.append(pageInfo);
builder.append(", posts=");
builder.append(posts);
builder.append("]");
return builder.toString();
}
}
public class PageInfo {
private String pageName;
private String pagePic;
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPagePic() {
return pagePic;
}
public void setPagePic(String pagePic) {
this.pagePic = pagePic;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PageInfo [pageName=");
builder.append(pageName);
builder.append(", pagePic=");
builder.append(pagePic);
builder.append("]");
return builder.toString();
}
}
public class Post {
private String postId;
private String postName;
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getPostName() {
return postName;
}
public void setPostName(String postName) {
this.postName = postName;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Post [postId=");
builder.append(postId);
builder.append(", postName=");
builder.append(postName);
builder.append("]");
return builder.toString();
}
}
Output:
BlogPost [pageInfo=PageInfo [pageName=TheTestbook, pagePic=content.jpg], posts=[Post [postId=123456, postName=Java Post]]]
Encapsulation in Java
What is encapsulation?
Encapsulation is the way of facilitating data abstraction. Data variables and methods can be binded together or en'capsulated' in a template called Class.
Consider a Car as an example. It has an encapsulated method runEngineToDrive().
runEngineToDrive()
As the class Car encapsulated the behavior runEngineToDrive(), if any new techniques are found to improve the engine efficiency, the class can implement the techniques in the method without the need for the users to worry about it. As the way of accessing class behavior/method w.r.t the user is not changed, the class can fully control the behavior on it's own.
This is possible because of this great Object Oriented feature encapsulation.
I can explain encapsulation with another real programming example
This example deals with the implementation of credit card transactions.
Every CreditCard must implement a behavior/method to pay the money by swiping it in the swiping machines at stores. The swiping machine is the user here using a CreditCard class swipeCard() method to deduct the money from customer account.
public class CreditCard{
public void swipeCard(){
System.out.println("Deducting money for the transaction..");
}
}
public class SwipingMachine {
public static void main(String[] args) {
CreditCard creditCard = new CreditCard();
creditCard.swipeCard();
}
}
Output : Deducting money for the transaction..
The credit card company decides to give a 5% cash back due to festival season and informed all the customers about the offer.
Now the programmers will update the swipeCard() method to deposit the 5% cash back to the users account without the swiping machine ( the user) to know about it. This is possible because the CreditCard class will control the behavior and not the user.
Now update the CreditCard class to add 5% cash back without updating anything in SwipingMachine..
public void swipeCard(){
System.out.println("Deducting money for the transaction..");
System.out.println("Credit 5% money for the transaction to customer account..");
}
The output will be updated to:
Deducting money for the transaction..
Credit 5% money for the transaction to customer account..
Java Annotations
Annotations are metadata about a program. Annotations will not have a direct effect on the operation of code they annotate.
An annotation looks like the following
@Test
@ symbol indicates the compiler that the text followed after @ is an annotation. In the following example Author is the annotation name.
@Author( name = "Thetestbook.com", date = "12/19/2015" )
class AnnotationTest() { ... }
What are the possible ways of applying annotations.
Annotations can be applied in many places like class, method, field and other program elements.
eg:
myString = (@NonNull String) refStr;Here @NotNull is an annotation to make sure the typecast string will not be null.
@Readonly is another useful annotation to create read only lists.
class UnmodifiableList<T> implements @Readonly List<@Readonly T> { ... }
Another useful annotation is SuppressWarnings to supress warnings of a method
@SuppressWarnings("deprecation") void useDeprecatedMethod() { }
Repeating annotations:
There are certain annotation types which will allow you to repeat some events on a timely basis. @Schedule is one of those annotations which is very useful in scheduling some events.
@Schedule(dayOfMonth="last") @Schedule(dayOfWeek="Fri", hour="23") public void doPeriodicCleanup() { ... }The above example will schedule the method run on last day of the month and also on Friday 11 PM every week. These kind of annotations are very useful in a production environment to cleanup / purge some files and unwanted data which will pile up during the processing.
@Alert(role="Manager") @Alert(role="Administrator") public class UnauthorizedAccessException extends SecurityException { ... }
Java Features
Simple
Java is a simple programming language. Learning and practicing Java is easy because of its resemblance with C and C++.Object-Oriented
Unlike C++, Java is a purely object oriented programming language. Java programs use objects and classes. A class is an idea or a model for creating objects. Object exists physically but class not exists physically. A class also contains variables and methods.Distributed
Information is distributed on various computers on a network. Using Java, we can write programs which capture information and distribute it to clients.Robust
Java programs will not crash easily because of its exception handling and its memory management features.Secure
Java enables the construction of virus-free and tamper-free systems.Architecture Neutral
Java’s byte code is not machine dependent. It can be run on any machine with any processor and with any OS.Portable
Java programs give same results on all machines. Every thing is clearly defined in Java specification and nothing is left to OS.Interpreted
Java programs are compiled to generate the byte code. This byte code can be downloaded and interpreted by the interpreter.High Performance
Along with interpreter there will be JIT compiler which enhances the speed of execution.Multithreaded
We can create different processing's in Java called threads. This is an essential feature to design server side programs. Thread is a process or execution.Dynamic
We can develop programs in Java which dynamically interact with the user on internet.Why Java is Platform Independent?
The Java compiler is an executable file and compiles Java source code to byte code (.class) which is then interpreted by the JVM to machine language instructions like any other native languages (eg: C Language).Here is an interesting aspect - Java Compiler is not platform independent but the byte code is. The byte code once compiled by any Java compiler in any platform can be interpreted by the JVM in other platforms thus making Java platform independent.
Merge sort java example
Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a merge sort on both halves
Divide by finding the number qq of the position midway between pp and rr. Do this step the same way we found the midpoint in binary search: add pp and rr, divide by 2, and round down.
Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. That is, recursively sort the subarray array[p..q] and recursively sort the subarray array[q+1..r].
Combine by merging the two sorted subarrays back into the single sorted subarray array[p..r].
Here's how merge sort uses divide-and-conquer:
Divide by finding the number qq of the position midway between pp and rr. Do this step the same way we found the midpoint in binary search: add pp and rr, divide by 2, and round down.
Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. That is, recursively sort the subarray array[p..q] and recursively sort the subarray array[q+1..r].
Combine by merging the two sorted subarrays back into the single sorted subarray array[p..r].
public class MergeSortJavaExample { public static void main(String[] args) { Integer[] a = {0, 2, 10, 5, -6, 7, 20, 2}; mergeSort(a); System.out.println(Arrays.toString(a)); } public static void mergeSort(Comparable [ ] a) { Comparable[] tmp = new Comparable[a.length]; mergeSort(a, tmp, 0, a.length - 1); } private static void mergeSort(Comparable [ ] a, Comparable [ ] tmp, int left, int right) { if( left < right ) { int center = (left + right) / 2; mergeSort(a, tmp, left, center); mergeSort(a, tmp, center + 1, right); mergeNumbers(a, tmp, left, center + 1, right); } } private static void mergeNumbers(Comparable[ ] a, Comparable[ ] tmp, int left, int right, int rightEnd ) { int leftEnd = right - 1; int k = left; int num = rightEnd - left + 1; while(left <= leftEnd && right <= rightEnd) if(a[left].compareTo(a[right]) <= 0) tmp[k++] = a[left++]; else tmp[k++] = a[right++]; while(left <= leftEnd) // Copy rest of first half tmp[k++] = a[left++]; while(right <= rightEnd) // Copy rest of right half tmp[k++] = a[right++]; // Copy tmp back for(int i = 0; i < num; i++, rightEnd--) a[rightEnd] = tmp[rightEnd]; } }
Output:
[-6, 0, 2, 2, 5, 7, 10, 20]
String notEquals java
There are many articles and examples about String equals() method and why not to use == for String comparison. While searching in google I find lot of questions about String notEquals() and how to find if a string notEquals another String. For Java programmers who have intermediate knowledge, this will be not much useful as they are aware of the concept of negation but I am writing this article to help beginners to understand the concept of notEquals while comparing Strings in their code.
Unfortunately the answer is 'No' but we can achieve it with negating equals() method.
The following example will demonstrate this concept.
Do we have notEquals() method in String API?
Unfortunately the answer is 'No' but we can achieve it with negating equals() method.
The following example will demonstrate this concept.
notEquals using Java String API
public class StringNotEquals {
public static void main(String[] args) {
String stringOne = "January";
String stringTwo = "March";
if(!stringOne.equals(stringTwo)){
System.out.printf("%s not equals to %s",stringOne, stringTwo);
}
else{
System.out.printf("%s equals to %s",stringOne, stringTwo);
}
}
}
Output: January not equals to March
Java switch statement with String - Example for String in a switch statement
Java 1.6 does not support Strings in a switch statement. From Java 1.7 on wards added support for Strings in a switch statement to allow ease for the programmers to code for Strings directly instead of relying on char or int to achieve this.
As String has so much importance in java, this decision is widely popular with Java community. This feature was requested by many developers from around 15 years.A switch with String cases is translated into two switches during compilation and there is a debate going in the community that this will add slowness compared to other decision blocks.It might be faster to just use If-Else-If instead of a hash for a string based switch.
The switch statement when used with a String uses the equals() method to compare the given expression to each value in the case statement and also case-sensitive - will throw a NullPointerException if the expression is null. So, it is advisable to check for null before using it in switch() to avoid any possible null pointer exception.
As String has so much importance in java, this decision is widely popular with Java community. This feature was requested by many developers from around 15 years.A switch with String cases is translated into two switches during compilation and there is a debate going in the community that this will add slowness compared to other decision blocks.It might be faster to just use If-Else-If instead of a hash for a string based switch.
The switch statement when used with a String uses the equals() method to compare the given expression to each value in the case statement and also case-sensitive - will throw a NullPointerException if the expression is null. So, it is advisable to check for null before using it in switch() to avoid any possible null pointer exception.
How to use string in switch - Java example :
public class StringInSwitchJava { public static void main(String[] args) { getMonth("FEB"); getMonth("NOV"); } public static void getMonth(String key) { switch (key) { case "JAN": System.out.println("I am January"); break; case "FEB": System.out.println("I am February"); break; case "MAR": System.out.println("I am March"); break; case "APR": System.out.println("I am April"); break; case "MAY": System.out.println("I am May"); break; case "JUN": System.out.println("I am June"); break; case "JUL": System.out.println("I am July"); break; case "AUG": System.out.println("I am August"); break; case "SEP": System.out.println("I am September"); break; case "OCT": System.out.println("I am October"); break; case "NOV": System.out.println("I am November"); break; case "DEC": System.out.println("I am December"); break; } } }
Output:
I am February
I am November
String compare java
.equals() method is used to compare Strings is Java.
String in java are immutable. whenever we try to modify the string you get a new instance. We cannot change the original string object
This has been done so that these string instances can be cached. A typical program contains a lot of string references and caching these instances can decrease the memory footprint and increase the performance of the program.
When using == operator for string comparison we are not comparing the contents of the string but are actually comparing the memory address of the string objects, if they are both equal it will return true and false otherwise. Whereas equals in string compares the string contents.
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().
String in java are immutable. whenever we try to modify the string you get a new instance. We cannot change the original string object
This has been done so that these string instances can be cached. A typical program contains a lot of string references and caching these instances can decrease the memory footprint and increase the performance of the program.
When using == operator for string comparison we are not comparing the contents of the string but are actually comparing the memory address of the string objects, if they are both equal it will return true and false otherwise. Whereas equals in string compares the string contents.
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().
public class StringCompare {
public static void main(String[] args) {
// These two have the same value
System.out.println(new String("test").equals("test"));
// --> true
// ... but they are not the same object
System.out.println(new String("test") == "test");
// --> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
System.out.println("test" == "test"); // --> true
// checks for nulls and calls .equals()
System.out.println(Objects.equals("test", new String("test")));
// --> true
System.out.println(Objects.equals(null, "test")); // --> false
}
}
Output:
true
false
true
true
false
== handles null strings fine, but calling .equals() from a null string will cause an exception:
Rounding a decimals to n number of places in Java
Why should we format numbers in applications?
In most of the applications, we may have a need to format the numbers to display them in a user friendly format. For example in accounting software, we might need to format a number as currency and limit the decimal to 2 places. In brokerage applications, we might have to display the percentage rounding the decimal part to n number of places.
The following example will demonstrate the concept of formatting numbers and rounding the decimal part to n number of places.
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DecimalRoundToXNumbers {
public static void main(String[] args) {
System.out.println(getDoubleRounded(111.15678, 2));
System.out.println(getDoubleRounded(111.15678, 3));
System.out.println(getDoubleRounded(111.15678, 4));
System.out.println(getDoubleRoundedAsCurrency(1234.2565));
}
/**
* @param doubleNum
* @param numOfPlaces
* @return formattedString
*/
private static String getDoubleRounded(Double doubleNum, int numOfPlaces){
//This is going to create a format string for the number of decimal places the user want
String formatterString = "#."+ new String(new char[numOfPlaces]).replace("\0", "#");
DecimalFormat decimalFormatter = new DecimalFormat(formatterString );
decimalFormatter.setRoundingMode(RoundingMode.CEILING);
Double roundedDouble = doubleNum.doubleValue();
return decimalFormatter.format(roundedDouble);
}
/**
* @param doubleNum
* @return currency formatted string
*/
private static String getDoubleRoundedAsCurrency(Double doubleNum){
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
currencyFormatter.setRoundingMode(RoundingMode.CEILING);
Double roundedDouble = doubleNum.doubleValue();
return currencyFormatter.format(roundedDouble);
}
}
Output:
111.16
111.157
111.1568
$1,234.26
Printing an object contents in Java without hashcode
How do I print a Java Object?
Some of you might be thinking that why should we print the contents of an object in the first place. Printing/showing the contents of an object is useful for debugging ,in the logs (if the information is not sensitive) and will be helpful in fixing some bugs as well.
The best method to show/print the contents of an object is by overriding the toString() method. If you are not going to override the toString() method and try to print the object, you will end-up seeing the hashcode of the object.
eg: Employee@7852e922
The following class is an example for overriding the toString() method.
public class Employee {
private String name;
private int id;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Employee [name=");
builder.append(name);
builder.append(", id=");
builder.append(id);
builder.append(", address=");
builder.append(address);
builder.append("]");
return builder.toString();
}
}
Now we are all set to show the contents of the Employee class correctly and the following class will be able to show you the contents using System.out.println
public class PrintObjectJava {
public static void main(String[] args) {
Employee employee = new Employee();
employee.setName("Ravi");
employee.setId(1);
employee.setAddress("Philadelphia");
System.out.println(employee);
}
}
Output: Employee [name=Ravi, id=1, address=Philadelphia]
Why should we override toString() method?
All classes by default extends Object class and whenever you print object of your class, toString() method of object will be invoked and this method is going to print the hash code of your object. If our intention is to print the contents rather than the hash code of the object, we should override toString() method to print property names and thier values.
Java Packages
A package in Java is an encapsulation mechanism that can be used to group
related classes,interfaces, and sub-packages.
The dot (.) notation is used to uniquely identify package members in
the package hierarchy.
Declaring a package:
A package hierarchy represents an organization of the Java classes and
interfaces. It does not represent the source code
organization of the classes and interfaces.
package syntax has the following syntax.
package <package name>;
Using a packages:
The accessibility of types (classes and interfaces) in a package may deny access
from outside the package.
The import declarations must be the first statement
after any package declaration in a source file. The simple form of the
import declaration has the following syntax:
import < type name>;
Important packages in Java:
java.lang:
This package got primary classes and interfaces
essential for java language. It consists
of wrapper classes, Strings, Threads etc. This package
is by default imported into
every java program.
java.util:
This package contains useful classes and interfaces like
stack, linkedlist, hashtable etc
java.io:
This package handles files and input /output related
tasks.
jawa.awt:
This package helps to develop GUI. It consists of an
important sub package
java.awt.event
javax.swing:
java.net:
client-server
programming can be done using this package
java.applet:
Applets are programs
which come from a server into a client and get executed on client machine.
java.sql:
This package helps to
connect to databases like oracle and utilize them in java.
Java Random Numbers
Random numbers are the sequence of numbers lack a defined pattern. For example 2,4,6,8 etc. are even numbers. 2,5,7,11 etc.. are prime numbers. By looking at the numbers we can relate a pattern in these series of numbers. But Random numbers will lack these kind of patterns and the next number in the sequence is unpredictable. eg: 1,2034, 33, 845 etc.
JDK provided a class Random to deal with Random numbers and you can use methods like nextInt(), nextDouble() etc to generate random numbers.
Here is a basic example.
This program will always produce a different double number whenever you run the program.
How to Generate a Random number in a range?
The following class will generate random numbers within a specified range.
Random numbers has many uses in statistics, gaming , cryptography and gambling software.
How to Generate Random numbers in Java?
JDK provided a class Random to deal with Random numbers and you can use methods like nextInt(), nextDouble() etc to generate random numbers.
Here is a basic example.
public class RandomNumberJavaBasic {
public static void main(String[] args) {
System.out.println(Math.random());
}
}
How to Generate a Random number in a range?
The following class will generate random numbers within a specified range.
public class JavaRandomNumbersInARange {
public static void main(String[] args) {
System.out.println(randomInt(1,10));
}
public static int randomInt(int min, int max) {
Random randomNumGenerator = new Random();
int randomNum = randomNumGenerator.nextInt((max - min) + 1) + min;
return randomNum;
}
}
Random numbers has many uses in statistics, gaming , cryptography and gambling software.
How to format String in Java Example?
import java.util.Formatter; import java.util.Locale; public class JavaStringFormatTest { public static void main(String[] args) { String javaString = "This %s is going to format %s program %d times"; /*As the String object is immutable, the formatter is going to use a StringBuilder * */ Formatter formatter = new Formatter(new StringBuilder(), Locale.US); /*This formatter is going to format the javaString to replace strings in place of %s and numbers for %d * */ formatter.format(javaString, "program", "java", 2); System.out.println(formatter); Formatter formatter2 = new Formatter(new StringBuilder(), Locale.US); /*This is going to change the format of the String in a different way * */ formatter2.format(javaString, "java", "program", 0); System.out.println(formatter2); } }
Output:
This program is going to format java program 2 times
This java is going to format program program 0 times
/*This is a basic program to format Local time */ public class JavaStringFormatLocaleTest { public static void main(String[] args) { String javaString = "Local time Now : %tT"; /*Here we are using the built-in object 'format' of System class to do the formatting * Calendar.getInstance() will give the local time and String will be formatted using %T for time * */ System.out.format(javaString, Calendar.getInstance()); } }
Output:(might change based on your local time)
Local time Now : 21:49:34
Importance of formatting in Java:
1. Formatting will be useful while printing the log statements in your Java programs.2. This will help unnecessary adding of Strings and will minimize coding standard violations.
3. The code will be much cleaner after formatting and maintenance of the code will be simple.
4. format method formats multiple arguments based on a format string.
d formats an integer value as a decimal value.
f formats a floating point value as a decimal value.
n outputs a platform-specific line terminator.
x formats an integer as a hexadecimal value.
s formats any value as a string.
tB formats an integer as a locale-specific month name.
Java String Class Example
Here is the basic String class example to create a new String object in Java and to append one String to another String object.
Output:
TheTestbook
TheTestbook
public class StringTest {
public static void main(String[] args) {
/* The following two declarations will create 2 new objects
* */
String string1 = "The"; // declaring a String - method1
String string2 = new String("Testbook");
// declaring a String
method2
System.out.println(string1 + string2);
// appending 2 String
//variables into one String. This will create a new object
System.out.println(string1.concat(string2));
//appending 2 Strings -
method 2
}
}
TheTestbook
TheTestbook
What is inheritance in Java?
One of the fundamental concepts of Java is inheritance. Inheritance is everywhere in Java. It's safe to say that it's almost (almost?)
impossible to write even the tiniest Java program without using inheritance.
It makes sense to inherit from an existing class Vehicle to define a class Car, since a car is a vehicle. Car will have a basic behavior and all child classes will extend this basic behavior from the parent class i.e Car without having a need to implement them.
It makes sense to inherit from an existing class Vehicle to define a class Car, since a car is a vehicle. Car will have a basic behavior and all child classes will extend this basic behavior from the parent class i.e Car without having a need to implement them.
IS-A
In OO, the concept of IS-A is based on class inheritance or
interface implementation. IS-A is a way of saying, "this thing is a type of that
thing." For example, a Mustang is a type of horse, so in OO terms we can say,
"Mustang IS-A Horse." Honda IS-A Car. Tomato IS-A Vegetable
A basic example of inheritance.
class One {
public One() {
System.out.println("one");
}
}
}
class Two extends One {
public Two() {
System.out.println("two");
}
}
}
class Demo
{
public static void
main(String args[]) {
Two t = new Two();
}
}
Output:
one
two
What is Java Class and Object?
A class denotes a category of objects, and acts as a blueprint for creating such objects.
A class models an abstraction by defining the properties and behaviors for the objects representing the abstraction.
An object exhibits the properties and behaviors defined by its class.
The properties of an object of a class are also called attributes, and are defined by fields in Java.
A field in a class definition is a variable which can store a value that represents a particular property.
The behaviors of an object of a class are also known as operations, and are defined using methods in Java. Fields and methods in a class definition are collectively called members.
/* Name of the class has to be "Main" only if the class is public. */
class JavaDemo
{
private String property1;
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
}
The process of creating objects from a class is called instantiation. An object is an instance of a class. Creating an object for class JavaDemo
JavaDemo demo = new JavaDemo();
"demo" is an object of class JavaDemo
The new operator returns a reference to a new instance of the JavaDemo class. This reference can be assigned to a reference variable of the appropriate class.
A class models an abstraction by defining the properties and behaviors for the objects representing the abstraction.
An object exhibits the properties and behaviors defined by its class.
The properties of an object of a class are also called attributes, and are defined by fields in Java.
A field in a class definition is a variable which can store a value that represents a particular property.
The behaviors of an object of a class are also known as operations, and are defined using methods in Java. Fields and methods in a class definition are collectively called members.
/* Name of the class has to be "Main" only if the class is public. */
class JavaDemo
{
private String property1;
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
}
The process of creating objects from a class is called instantiation. An object is an instance of a class. Creating an object for class JavaDemo
JavaDemo demo = new JavaDemo();
"demo" is an object of class JavaDemo
The new operator returns a reference to a new instance of the JavaDemo class. This reference can be assigned to a reference variable of the appropriate class.
How to Install Java in windows?
How to Install Java in Windows:
Here are the system requirements to install Java 8 in a windows system.
At-least 128 MB of RAM
Windows 7 , 8.X, Vista or higher
130 MB of free disk space
Any Modern browser
Download new Java build here
Once the installation file is downloaded - Run the file
Click on install to start the installation of Java.
If you want to change the destination folder. You can change it as show in the image.
You will be shown with "You have successfully installed Java" Dialog if the installation is successful after few dialog.
Check the version of Java:
You can check the installed version of Java using the command 'java -version'
You can create a sample Java program by followinf this article How to code a Basic Program in Java
JVM Components
Class Loader subsystem does the following:
It loads .class files into memory.
It verifies byte code instructions in that .class files.
Then it will allocate required memory to run the program.
This memory is divided into 5 blocks called Run Time Data Area. They are:
Method Area:
The class code & method code is available in method area.Heap:
Objects are created on Heap.Java Stacks:
Java methods are executed in Java stacks. Java stacks have frames to execute methods separately one method in one frame.PC Registers:
Program counter registers contain memory address of instructions to be executed by microprocessor.Native Method Stacks:
Native methods are executed on Native method stacks. Execution Engine contains Interpreter & JIT compiler which converts byte code instructions to machine language instructions. Then the processor will execute them.Naming Conventions
The rules related to writing names of packages, classes, methods etc.
Package names in java are written in all small letters.
Ex:- java.awt, java.io
Each word of class names and interface names start with a capital.
Ex:- String
Method names start with a small letter, then each word start with a capital.
Ex:- println( ), readLine( )
Variable names also follow the above rule.
Ex:- age, empName
Constants should be written using all capital letters.
Ex:- PI
All keywords should be written in all smaller letters.
Ex:- public, void
The best naming convention is to choose a variable name that will tell the reader of the program what the variable represents. Variable names that describe the data stored at that particular memory location are called mnemonic variables. For example, if you wish to store a grade on a test, a variable name such as grade would be more easily remembered than a variable name such as var2.
Package names in java are written in all small letters.
Ex:- java.awt, java.io
Each word of class names and interface names start with a capital.
Ex:- String
Method names start with a small letter, then each word start with a capital.
Ex:- println( ), readLine( )
Variable names also follow the above rule.
Ex:- age, empName
Constants should be written using all capital letters.
Ex:- PI
All keywords should be written in all smaller letters.
Ex:- public, void
Choosing a variable name:
The best naming convention is to choose a variable name that will tell the reader of the program what the variable represents. Variable names that describe the data stored at that particular memory location are called mnemonic variables. For example, if you wish to store a grade on a test, a variable name such as grade would be more easily remembered than a variable name such as var2.
Rules for naming variables:
- All variable names must begin with a letter of the alphabet, an underscore, or ( _ ), or a dollar sign ($). The convention is to always use a letter of the alphabet. The dollar sign and the underscore are discouraged.
- After the first initial letter, variable names may also contain letters and the digits 0 to 9. No spaces or special characters are allowed.
- The name can be of any length, but don't get carried away. Remember that you will have to type this name.
- Uppercase characters are distinct from lowercase characters. Using ALL uppercase letters are primarily used to identify constant variables. Remember that variable names are case-sensitive.
- You cannot use a java keyword (reserved word) for a variable name.
5 simple ways to print java array
You can print a Java array in so many different ways depending upon your Java version. I have collated 5 easy and simple ways to print arrays in Java.
Output:
[1, 2, 3, 4, 5]
[John, Mary, Bob, Don, Chris]
12345
JohnMaryBobDonChris
1, John, 2, Mary, 3, Bob, 4, Don, 5, Chris,
[John, Mary, Bob, Don, Chris]
1, 2, 3, 4, 5,
John, Mary, Bob, Don, Chris,
import java.util.Arrays;
public class Simple5WaysToPrintJavaArray {
public static void main(String[] args) {
int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob", "Don", "Chris"};
//Method 1 - This will be useful to print using prior versions of Java 8
System.out.println(Arrays.toString(intArray));
System.out.println(Arrays.toString(strArray));
// Method 2 - In Java 8 we have lambda expressions
Arrays.stream(intArray).forEach(System.out::print);
System.out.println("");
Arrays.stream(strArray).forEach(System.out::print);
System.out.println("");
//Method 3 - using a for loop - using one loop as the lengths are same
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + ", ");
System.out.print(strArray[i] + ", ");
}
System.out.println("");
//Method 4 - using Arrays.asList - only works with String as int is primitive
System.out.println(Arrays.asList(strArray));
//Method5 - using extended for loop from Java 5
for(int i:intArray){
System.out.print(i+ ", ");
}
System.out.println("");
for (String str : strArray) {
System.out.print(str+ ", ");
}
}
}
Subscribe to:
Posts (Atom)