Posts

Showing posts from June, 2019

RTE

Stands for "Runtime Environment." As soon as a software program is executed, it is in a runtime state. In this state, the program can send instructions to the computer's processor and access the computer's memory (RAM) and other system resources. When software developers write programs, they need to test them in the runtime environment. Therefore, software development programs often include an RTE component that allows the programmer to test the program while it is running. This allows the program to be run in an environment where the programmer can track the instructions being processed by the program and debug any errors that may arise. If the program crashes, the RTE software keeps running and may provide important information about why the program crashed. When you see the name of a software program with the initials "RTE" after it, it usually means the software includes a runtime environment. Program: public class RTE{ public

Data Structures In Java

The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes − Arrays Linked lists Stack Queue Tree ArrayList Hashmap Treemap Treeset

Thread Synchronization In Java

Synchronization in java is the capability to control the access of multiple threads to any shared resource.Java Synchronization is better option where we want to allow only one thread to access the shared resource.The synchronization is mainly used to To prevent thread interference. To prevent consistency problem. Types of Synchronization There are two types of synchronization: Process Synchronization Thread Synchronization Here, we will discuss only thread synchronization. Thread Synchronization: There are two types of thread synchronization mutual exclusive and inter-thread communication. Java synchronized method: If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

Multi-threading in Java

Multi-threading in java is a process of executing multiple threads simultaneously.However, we use multi-threading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multi-threading is mostly used in games, animation, etc. Advantages of Java  Multi-threading 1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time. 2) Yo can perform many operations together, so it saves time. 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread. Multi-threading can be achieved in two ways: 1. Extending the Thread class 2. Implementing the Runnable Interface Thread creation by extending the Thread class We create a class that extends the java.lang.Thread class. This class overrides the run() method avail

Threads in Java

Thread: Facility to allow multiple activities within a single process Referred as lightweight process A thread is a series of executed statements Each thread has its own program counter, stack and local variables A thread is a nested sequence of method calls Its shares memory, files and per-process state Need of a thread: To perform asynchronous or background processing Increases the responsiveness of GUI applications Take advantage of multiprocessor systems Simplify program logic when there are multiple independent entities When a thread is invoked, there will be two paths of execution. One path will execute the thread and the other path will follow the statement after the thread invocation. There will be a separate stack and memory space for each thread. Every java program creates at least one thread [ main() thread ]. Additional threads are created through the Thread constructor or by instantiating classes that extend the Thread class.

File Handling

File handling in Java using FileWriter and FileReader Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information as these are Byte stream classes. FileWriter: FileWriter is useful to create a file writing characters into it.This class inherits from the OutputStream class.The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.FileWriter creates the output file , if it is not present already. Constructors: FileWriter(File file) – Constructs a FileWriter object given a File object. FileWriter (F

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java. try: The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch: The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally: The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. throw: The "throw" keyword is used to throw an exception. throws: The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature. Java Exception Handling Example public class JavaExceptionExample{   public static

Exceptions in Java

Image
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Error vs Exception Error: An Error indicates serious problem that a reasonable application should not try to catch. Exception: Exception indicates conditions that a reasonable application might try to catch.                                                       Exception Hierarc hy

Strings In Java

Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Below is the basic syntax for declaring a string in Java programming language. Syntax: <String_Type> <string_variable> = “<sequence_of_string>”; Example: String str = "Bikramjot"; Java String Methods String charAt()  StringcompareTo() String concat() String contains() String endsWith() String equals() equalsIgnoreCase() String format() String getBytes() String getChars() String indexOf() String intern() String isEmpty() String join() String lastIndexOf() String length() String replace() String replaceAll() String split() String startsWith() String substring() String toCharArray() String toLowerCase() String toUpperCase() String trim() String valueOf()

Interface In Java

Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).   Interfaces specify what a class must do and not how. It is the blueprint of the class. An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement. If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract. A Java library example is, Comparator Interface. If a class implements this interface, then it can be used to sort a collection. Syntax : interface <interface_name> {   // declare constant fields // declare methods that abstract // by default. } To declare an interface, use interface keyword. It is used to provide total abstraction. That m

Abstract Class in Java

In C++, if a class has at least one pure virtual function, then the class becomes abstract. Unlike C++, in Java, a separate keyword abstract is used to make a class abstract.  An example abstract class in Java  abstract class Shape {   int color;   // An abstract function (like a pure virtual function in C++)   abstract void draw();   }  Following are some important observations about abstract classes in Java. 1) Like C++, in Java, an instance of an abstract class cannot be created, we can have references of abstract class type though. 2) Like C++, an abstract class can contain constructors in Java. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program. 3) In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited. 4) Abstract classes can also have final method

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java: For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability. Types of Inheritance: Single Multi-level Multiple Hybrid

Constructors in Java

Java Constructors: A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes: Example: public class MyClass { int x;  // Create a class attribute public MyClass() { x = 5;   } public static void main(String[] args) { MyClass myObj = new MyClass(); //constructor object System.out.println(myObj.x); // Print the value of x } } Types of Constructors: Default constructor No arg Constructor Parameterized Constructor

Object Oriented Programming in java

Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. OOPs Concepts: Polymorphism: The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. Inheritence: Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the d

Java - pass by value or pass by Reference

One of the biggest confusion in Java programming language is whether java is Pass by Value or Pass by Reference. I ask this question a lot in interviews and still see interviewee confused with it. So I thought to write a post about it to clarify all the confusions around it. Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

Methods

A method is a block of code which only runs when it is called.You can pass data, known as parameters, into a method.Methods are used to perform certain actions, and they are also known as functions.Methods are used to reuse code: define the code once, and use it many times. Create a Method A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions: Example: Create a method inside MyClass: public class MyClass { static void myMethod() {  // code to be executed } }

ARRAYS

Image
An array is a group of like-typed variables that are referred to by a common name.Arrays in Java work differently than they do in C/C++. Following are some important point about Java arrays.These are Homogeneous. How arrays are stored in memory: Reference copy: Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other object to reference passed inside method, the object from calling method as well its reference will remain unaffected. Array Syntax: int intArray[];    //declaring array intArray = new int[20];  // allocating memory to array OR int[] intArray = new int[20]; // combining both statements in one Arrays can be 2-D, 3-D upto N-D. N-D array is collection of  N-1 arrays.

Loops

1. while loop: Syntax : while (boolean condition){ loop statements... } 2. for-loop: Syntax:  for (int x = n; x <= n; x++) {  statements;   }  3. Enhanced For loo p Syntax: for (T element:Collection obj/array){ statement(s) } 4. do-while: Syntax: do{ statement(s1); } while{ statement(s2); }

Conditions

Java has following conditional statements: 1. if statement 2. nested if statement 3. if-else statement 4. if-else-if statement 5. Switch Case Statement 1. if statement: Syntax: if(condition){ Statement(s); } 2. Nested if statement: Syntax: if(condition_1) { Statement1(s); if(condition_2) { Statement2(s); } } 3. if-else statement: Syntax: if(condition) { Statement(s); } else { Statement(s); } 4. if-else-if statement: if(condition_1) { statement(s); } else if(condition_2) { statement(s); } else { statement(s); } 5. Switch Case: Syntax: switch(expression) {  case valueOne:  statement(s) break;  case valueTwo:  statement(s break;  default: statement(s)

Operators

Operators: Operators are tokens which perform calculations when applied to variables. There are many types of operators in java such as: Arithmetic operators Relational operators Logical operators Bit wise operators  Assignment operator  Conditional operators