Tumgik
techandguru-blog · 5 years
Link
Tumblr media
Odd one out
Can you answer this simple aptitude MCQ on odd one? I am sure you cannot. Do you think you can prove me wrong? #aptitudemcq #competition #interview
Tip: Follow us on Facebook, Twitter to new MCQs to stay ahead in preparations
3 notes · View notes
techandguru-blog · 5 years
Link
Tumblr media
Java final keyword
Can you answer this MCQ on java final keyword? This question is asked in recently java interviews but only a few could answer this question. #programming #java #javamcq #interview #programmers
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Java datatype mcq
Can you answer this recently asked java datatype interview question? Only a few could answer it correctly. So What is your answer? #programming #java #interview #javamcq
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Java final keyword
Are you sure about the use of java final keyword? Only a few java geeks could answer this question. What is your answer? #programming #java #interview #programmers
Tip: follow us on medium
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Java Array MCQ
Only a few could answer this question on Java arrays asked in interviews. Can you answer it correctly? So Let's see... #programming #interview #android #career
0 notes
techandguru-blog · 5 years
Link
Just like main() method, finalize() method is also important. finalize() has protected access. It is the last method called before cleanup. Through the finalize() method you can release system resources. Since it is the last method before the GC cleanup, incorrect usages of finalize() method can lead to trouble.
Typical finalize() method usages problem
First and the foremost problem is not using finalize(). This is because the finalize() method gives you a last-minute chance to release any system resources. If you do not release resources then it may lead to an inconsistent state of the resource. Which eventually impacts resource utilization as a whole.
finalize() method is called only once by GC. If you do not implement the finalize() method correctly, your object may remain in memory and can not be cleared by GC thereafter. So you have just one shot to do all cleaning and releasing successfully. GC DO NOT CALL finalize() MORE THAN ONCE.
finalize has protected access. So any Java class can override it. But while overriding if you do not call superclass finalize(), your superclass will not be captured by GC. This will lead to memory leaks and so on.
finalize() method is intended to be called by GC so calling like other normal method is not advisable.
Exceptions thrown by finalize() are ignored by GC. So do not do any error/exception handling here
So looking at the above points, you should clearly understand how important it is to use finalize() with due attention. Improper usage of finalize() will cost you time and you will invite bigger troubles in terms of memory utilization and poor resource utilization. Eventually, it will make your program slow and sluggish. So better pay attention early to avoid later problems.
That's it. Hope you like the article. Please comment, share and subscribe
0 notes
techandguru-blog · 5 years
Link
Did you use the static keyword in java? Do you know what problems are you inviting yourself? This post will explain to you all. So before moving into problems, let's understand common usages of static keyword
used to create class variables
used to declare static method/ class methods
used to declare static nested classes
used to declare static constant strings
used to declare shared variables and so on
Above points regarding the use of static variable are quite self-explanatory and if you want to see more detail visit java class properties. static items are allocated memory before any instance creation. Since static items are accessible anywhere in the program depending upon access modifier. So improper use of static variable can invite bigger problems in the long run. Let's have a look at them
Improper use of static keyword and problems
sometimes static variable is used by programmers to travel data from one component/class to another. This is a big problem. Firstly, we are breaking OOPs and modular architecture. Secondly, in complex projects, dirty value problem rises because the same variable can be updated or manipulated by a different thread. So we should avoid.
If we do not pay proper attention to deciding what should be class variable and class method, it will become cumbersome to change in complex projects. Sometimes whole projects are impacted.
static items occupy memory until the end of execution. So improper use of static variable can invite memory issues
So, you should pay proper attention to use static keyword. it gives us power but always remember power comes with responsibilities.
Guys, please add if I missed anything, also comment share, and subscribe
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Here is another trending Java Array Interview Question, can you answer this? #programming #interview #programmer
You may like Java Arrays and Interview Question
Please like share and subscribe to stay updated on the latest interviews
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Java Interview Question
I am surprised if you can answer this recently asked java interview question? Please write your answer in the comment box. #programming #startups #careers #java
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Java Interview Question
Can you predict the right output of the Java code snippet? Most programmers failed to answer this recently asked Java Interview question. #programming #technology #android #java #interview #startups
You can visit the related content at Java Operators and Java Exceptions
Please like share and subscribe to stay updated on the latest post
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Java Interview Question
Do you think you can answer this? This question is actively asked in Java Interviews. Write your answer in the comment box below. #programmers #java, #exception #jobseekers
You can visit Java Exception in Handling or Java Basic Concepts to refresh your concepts
0 notes
techandguru-blog · 5 years
Link
There are times when we do not know the exact item but we know how it looks like i.e. it has specific pattern and certain characteristics. So by just knowing the pattern, we can identify the items. In the same way, there are patterns to identify strings or set of strings in given text or file in java. For that, we have a REGULAR EXPRESSION in java. e.g. if we want to catch all email from the given text, we know how emails look like so we can define a pattern. We create a regex to represent that pattern. And performing pattern match on the given text, we can list all the emails in the given input text.
So regular expression is a special sequence of character that helps to match, find, edit other string or set of strings in the given input, using a specialized string held in so-called Pattern. The regular expression in java is provided through java.util.regex package. Java.util.regex primarily contains three classes name listed below
- Pattern Class: It is used to define the patterns for matching. An object of Pattern class represents a compiled representation of the regular expression. There is no public constructor available to create an object of Pattern class. To instantiate an object of Pattern class, one has to use any version of public static compile() method of Pattern class. These methods accept regular expression string as the first argument.
- Matcher Class: Matcher class is an engine to interpret the pattern of regular expression and performs the match on the input string. Matcher class too does not have any public constructor. To obtain an object of Matcher class, one has to use call matcher() method on Pattern Class object.
- PatternSyntaxException Class: A PatternSyntaxException class represents an unchecked exception that indicates a Syntax error in the regular expression.
CAPTURING GROUP in Regular Expression
The capturing group represents the group of the letter put together as a single unit. They are created by putting letters to be grouped in parentheses. e.g. (techie360).
Capturing groups are numbered by counting the opening parentheses from left to right. e.g ((t)(pq)) has capturing group in the order ((t)(pq)), (t), (pq).
To find the number of capturing group in the regular expression, just use groupCount() method on Matcher class object. Every capturing group contains group 0 which is not included in the count returned by groupCount().
Example of Capturing Group usage
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { // input String String line = "you are reading post on techie360!"; String pattern = "(.*)(\\d+)(.*)"; // Create a Pattern object Pattern p = Pattern.compile(pattern); // Now create matcher object. Matcher m = p.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); }else { System.out.println("NO MATCH"); } } }
The output of the above program would be
Found value: you are reading post on techie360! Found value: you are reading post on techie360! Found value: 0
REGULAR EXPRESSION SYNTAX AND MEANING
In the below table, a complete list of regular expression letters are listed
Regex Meaning ^ Matches the beginning of the line. $ Matches the end of the line. . Matches any single character except a newline. Using m option allows it to match the newline as well. [...] Matches any single character in brackets. [^...] Matches any single character not in brackets. \A Beginning of the entire string. \z End of the entire string. \Z End of the entire string except for allowable final line terminator. re* Matches 0 or more occurrences of the preceding expression. re+ Matches 1 or more of the previous thing. re? Matches 0 or 1 occurrence of the preceding expression. re{ n} Matches exactly n number of occurrences of the preceding expression. re{ n,} Matches n or more occurrences of the preceding expression. re{ n, m} Matches at least n and at most m occurrences of the preceding expression. a| b Matches either a or b. (re) Groups regular expressions and remembers the matched text. (?: re) Groups regular expressions without remembering the matched text. (?> re) Matches the independent pattern without backtracking. \w Matches the word characters. \W Matches the nonword characters. \s Matches the whitespace. Equivalent to [\t\n\r\f]. \S Matches the non-whitespace. \d Matches the digits. Equivalent to [0-9]. \D Matches the non-digits. \A Matches the beginning of the string. \Z Matches the end of the string. If a newline exists, it matches just before newline. \z Matches the end of the string. \G Matches the point where the last match finished. \n Back-reference to capture group number "n". \b Matches the word boundaries when outside the brackets. Matches the backspace (0x08) when inside the brackets. \B Matches the nonword boundaries. \n, \t, etc. Matches newlines, carriage returns, tabs, etc. \Q Escape (quote) all characters up to \E. \E Ends quoting begun with \Q.
METHODS OF MATCHER CLASS
Matcher class methods can be divided into three categories basis the function they perform:
- Index Methods: index methods provide the index of match found in the input string. Below is the list of index methods:
Method Explanation public int start() Returns the start index of the previous match. public int start(int group) Returns the start index of the subsequence captured by the given group during the previous match operation. public int end() Returns the offset after the last character matched. public int end(int group) Returns the offset after the last character of the subsequence captured by the given group during the previous match operation.
- Study Methods: these methods perform match on the input string and return whether the match is found or not. Please see below list for all Study methods:
Method Description Public boolean lookingAt() Attempts to match the input sequence, starting at the beginning of the region, against the pattern. public boolean find() Attempts to find the next subsequence of the input sequence that matches the pattern. public boolean find(int start) Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index. public boolean matches() Attempts to match the entire region against the pattern.
REPLACEMENT METHODS:
These methods perform replacement in the input string. Below are replacement methods
Method & Description public Matcher appendReplacement(StringBuffer sb, String replacement) Implements a non-terminal append-and-replace step. public StringBuffer appendTail(StringBuffer sb) Implements a terminal append-and-replace step. public String replaceAll(String replacement) Replaces every subsequence of the input sequence that matches the pattern with the given replacement string. public String replaceFirst(String replacement) Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string. public static String quoteReplacement(String s) Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class.
matches() and lookingAt() methods: Similarity and differences
- both methods match pattern in the input string
- both start matching at the start of input string
- matches() requires complete string to be matched but lookingAt() does not require the complete string to be matching.
To demonstrate the difference see the example below:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexMatches { private static final String REGEX = "too"; private static final String INPUT = "tooo"; private static Pattern pattern; private static Matcher matcher; public static void main( String args[] ) { pattern = Pattern.compile(REGEX); matcher = pattern.matcher(INPUT); System.out.println("REGEX is: "+REGEX); System.out.println("INPUT is: "+INPUT); System.out.println("lookingAt(): "+matcher.lookingAt()); System.out.println("matches(): "+matcher.matches()); } }
the output of the above program
REGEX is: foo INPUT is: fooooooooooooooooo lookingAt(): true matches(): false
- replaceFirst( ) replaces first matching occurrence and replaceAll() replaces all occurrences of the pattern matching.
So we understand how we can use regular expression in java for pattern matching. Regular expressions are quite a powerful tool in java to find, edit and replace the input string.
Hope you enjoyed the article, please share and subscribe to the latest article update.
1 note · View note
techandguru-blog · 5 years
Link
From very early school days, we are familiar with writing notebooks and reading school books, novel, stories, etc. Keeping notes of important items help us remembering and planning our stuff. Similarly, we have files in java. Even java programs are files themselves. Files in java are made available through java.io.File package and java.io package contains literally everything needed for IO operations. IO operations are handled through Stream. A stream is a sequence of bytes and represents an input source and output source. Streams in java.io support almost all data types like primitives and objects.
STREAMS IN JAVA
A stream can be defined as a sequence of data. There are two types of streams
- InputStream: used to read data from the stream
- OutputStream: used to write/append data to stream
In the program, data flows in through inputStream and flows out using outputStream. Java has strong IO supports for both files and network IO operations.
STREAMS AVAILABLE IN JAVA
Byte Stream: byte stream contains byte as unit of data and all input/output operations are performed in the quantum of byte (8 bit). There is a number of implementations of BYTE STREAM but popularly used streams are FileInputStream and FileOutputStream. See the example below to understand byte streaming
import java.io.*; public class ByteStreamExample { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
Above program reads byte by byte from file input.txt and writes data to output.txt. Once the reading/writing is done, both the files are closed in the finally{} clause.
Character Stream in Java
It reads two bytes at a time represent Unicode and writes two bytes of Unicode. The commonly used character stream implementations are FileReader and FileWriter. These wraps the FileInputStream and FileOutputStream respectively.
Standard Stream: Standard streams are used to take input from input peripheral devices like keyboard and writes to output devices like display of the computer. Every programming language provides supports for taking input from the keyboard and writing output to the computer display. Java provides 3 basic standard streaming implements:
- Standard Input: represented by Standard.in and used to provide input stream to computer programs.
- Standard Output: usually writes output to the computer screen. It is defined in Standard.out. It provides a standard output stream for computer output devices.
- Standard Error: used to display output error produced by computer programs. It is represented as Standard.error
Example of reading from the keyboard using standard input
import java.io.*; public class ReadFromKeyboard { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != 'q'); }finally { if (cin != null) { cin.close(); } } } }
Above program goes on reading and once the user enters ‘q’ program exits.
INPUT-OUTPUT OPERATIONS ON FILES IN JAVA
IO on files are done using FileInputStream and FileOutputStream. Below image shows complete file io stream implementation in java.
FileInputStream: used to read data from the file. An object of FileInputStream can be created an either passing path of file or File object instance like below
InputStream f = new FileInputStream("C:/techandguru/file"); File f = new File("C:/techandguru/file"); InputStream f = new FileInputStream(f);
Methods provided by FileInputStream are listed in below table with description
Method Description public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. public int read(int r)throws IOException{} This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file. public int read(byte[] r) throws IOException{} This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned. public int available() throws IOException{} Gives the number of bytes that can be read from this file input stream. Returns an int.
FileOutputStream
FileOutputStream creates a file if not present and then opens the output stream to write data to the file. Like FileInputStream, FileOutputStream also has two constructors to create an object. Both are shown in the example
OutputStream f = new FileOutputStream("C:/techandguru/file") //take path to file File f = new File("C:/techandguru/file"); OutputStream  f = new FileOutputStream(f); // takes File class object as argument
Methods and description of FileOutputStream Class
Method Description public void close() throws IOException{} This method closes the file output stream and flushes the data in the file. Releases any system resources associated with the file. Throws an IOException. protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. public void write(int w)throws IOException{} This method writes the specified byte to the output stream. public void write(byte[] w) Writes w.length bytes from the mentioned byte array to the OutputStream.
File, FileReader, FileWriter in Java
File class in java provides various utility methods to manage file and directories. The directory is a File which can contain other Directories and Files. File Class provides a way to create and list all directories of the given physical path on the machine.
File class provides mkdir() and mkdirs() methods to create the directory on the specified path in argument.
- mkdir() method is used to create a directory. It does not create a parent directory. It returns true on the successful creating directory and false otherwise. It could fail for various reasons like if permission is denied, if the path does not exist or if there is a directory already present.
- mkdirs() method is used to create directory and parent directories if not present.
- list() method is used to list all the files and directories on the specified path.
Below example list all the directories on the path “/temp”
import java.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // create file object file = new File("/temp"); // list all files and directories on the path paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } } catch (Exception e) { // if any error occurs e.printStackTrace(); } } }
Java also provides an implementation for reading and writing character streams to files through FileReader and FileWriter. FileReader is implementation on InputStream and is used to read data from the file. FileWriter is implementation on OutputStream and is used to write character stream to files.
0 notes
techandguru-blog · 5 years
Link
Tumblr media
Java MCQ
It seems a simple java coding MCQ but 90% failed to answer correctly. What's your answer? #jobseekers #lookingforjob #java #techandguru
Write your answer in the comment box below and share
Related Post: Interview Preparation and Java Exceptions and Error
0 notes
techandguru-blog · 5 years
Text
Patient pays
Believe and keep hustling
Tumblr media
3K notes · View notes
techandguru-blog · 5 years
Text
“Believe in yourself! Have faith in your abilities! -Norman Vincent Peale”
52 notes · View notes
techandguru-blog · 5 years
Link
Do you understand the Java Operators? Only a few could answer the below question? What’s your answer? #jobseekers #lookingforjob #java
Tumblr media
Java Operator
Please write your answer in the comment box below and share this post.
Related Posts: Java Interview Preparation and Java Operator Basics
1 note · View note