Skip to main content

Posts

Showing posts with the label core-java

Stream In Java

stream in java 8 : Stream API is used to process collection of objects. stream() method is present in Collection interface from package java.util . Stream is an interface present in java.util package, filter() and map() methods are present in Stream interface. -->when to use filter()  method ? If we want to filter elements from collection based on some boolean condition then we can use filter() method.  for example  : filtering even or odd numbers from list of numbers. -->When to use map()  method ? If we want to create new object for every object in collection then we should use map() method. for example : if we want to increase every number in list by 2 , here every object is getting modified ,we have to use map() in this type of scenario. In below example , we used both filter() and map() methods on stream , inside filter method we applied some condition and in map method we are transforming our object to different one. package com.crtr4u.www; import java...

Collections - List Interface In Java

Iterable Interface - Root Interface of all collection classes. Collection Interface - extends Iterable Interface. List , Queue , and Set Interfaces extends Collection Interface. List Interface In Java : List can have duplicate values. List interface is implemented by classes : ArrayList,LinkedList,Vector,Stack. ArrayList : ArrayList maintain insertion order and is non-synchronized , elements stored in ArrayList can be accessed randomly.It internally uses dynamic array,In ArrayList searching is fast because of indexing. In below example we have created an ArrayList , added elements in it and iterated using for each loop and using iterator . import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class CollectionDemo { public static void main(String[] args) { List<String> studentList= new ArrayList<String>(); studentList.add("Neel"); studentList.add("Pooja"); studentList.add("Shivam"); System.out.println(...

Java 8 features - Functional Interface and Lambda Expression

Functional Interface in Java Functional Interface is defined as an interface with only one abstract method .one of the example of Functional interface in java.lang package is Runnable with only one abstract method run() . we can use Annotation , @FunctionalInterface to create Functional interface in java , actually this annotation is not mandatory , but if we write this annotation , and in future if somebody try to add new abstract method in our interface then he will get Error as  : Invalid '@FunctionalInterface' annotation. Functional Interfaces are also called as Single Abstract Method ( SAM ) interfaces. Using Functional Interfaces,Anonymous Inner classes are implemented. Example : public class TestAnonymousInnerClass { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println("Implementing Runnable"); } }).start(); } } Output : Implementing Runnable Lambda Expressions in java Lam...

Java 8 features ,Default Methods and Static Methods

 Java as an Object oriented programming language was invented in the early 90s. In year 2005 , added major changes such as : 1.Enhanced for loops 2.Generics 3.Type-safe enumerations. 4.Annotations. again after 10 years , in 2015 java 8 was introduced with lot of new features : such as : 1.Lambda Expressions 2.Method References 3.Default methods 4.New Stream API 5.New Date/Time API 6.Nashorn -> now in java 8 ,interface introduced with some new changes. interface can now define static methods. interface can now define default methods. package com.suv.java8; public class Java8Demo implements Calculator { public static void main(String[] args) { System.out.println("Welcome to https://www.crtr4u.com/"); Java8Demo jd = new Java8Demo(); jd.msgDisplay(); Calculator.sayHi(); } } interface Calculator { default void msgDisplay() { System.out.println("this is default method introduced in java 8 interface"); } static void sayHi() { System.out.println("Hi...

Program to Prove String is immutable and String Builder is Mutable

In our last article , we understood difference in String vs String Builder vs String Buffer  , as you know String is immutable and String Builder and String Buffer is mutable ,see below example to understand concept clearly : public class StringPractice { public static void main(String[] args) { String name="Swapnil"; System.out.println("original name "+name); System.out.println("modifying name as "+name.concat("Vyawhare")); System.out.println("*********************final name using String : "+name); StringBuilder name2=new StringBuilder("Swapnil"); System.out.println("original name "+name2); System.out.println("modifying name as "+name2.append("Vyawhare")); System.out.println("*********************final name using StringBuilder :"+name2); StringBuffer name3=new StringBuffer("Swapnil"); System.out.println("original name "+name3); Sy...

String vs StringBuffer vs StringBuilder

String is immutable whereas StringBuffer and StringBuilder are mutable classes. String is one of the most widely used classes in Java. StringBuffer and StringBuilder classes provide methods to manipulate strings. Since String is immutable in Java,whenever we do String manipulation like concatenation, sub-string, etc.it generates a new String.So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation. StringBuffer vs StringBuilder StringBuffers all public methods are synchronized. StringBuffer provides Thread safety but at a performance cost , it reduce performance. In most of the scenarios, we don’t use String in a multithreaded environment. So Java 1.5 introduced a new class StringBuilder,  which is similar to StringBuffer except for thread-safety and synchronization. StringBuffer has some extra methods such as substring, length, capacity, trimToSize, etc. However,these are not required since you have all these present in String too. ...

String In Java

String class available in  java.lang package . java.lang.String String in java is defined as , an object that represents sequence of characters.In java , objects of String are immutable which means a constant , and can not be changed once created. String class provide various important method like :  toUpperCase() - convert String to upper case. toLowerCase()  - convert String to lower case. length() - to check length of String. concat() - to concatenate two String . split() - to split String. and many other methods ,each method is used to perform some operation on String value. Ways To Create String in Java : check below program where we are creating String type variable using different ways : public class StringDemo { public static void main(String[] args) { String websiteUrl="https://www.crtr4u.com"; String subject=new String("java programming"); char charArray[] = {'P','Q','R','S','T'}; String strFromCharArray...

Java 8 Features Part -1

Java 8 introduced benefits of Functional Programming in java. Lambda Expression :  Lambda is an anonymous function in java , a function without name ,return type and access modifier. In java , normally we write method as below : Example :Without Lambda public void run(){ System.out.println("Welcome to www.crtr4u.com"); } using lambda expression same method can be written as:      ()->System.out.println("Welcome to www.crtr4u.com"); if we have multiple statements then we can use brackets, Lambda Expression also known as anonymous function or closures. Example : without using lambda : public void add(int num1,int num2){ System.out.println(num1+num2); } above example can be written using lambda expression as : (int num1,int num2)->System.out.println(num1+num2); Why To Use Lambda Expression :  1.Easy to implement and Less Code as shown in above example.  2.We can pass lambda expression as paramater to other method. To implement Lambda Expr...

Java Interview Topic - How To Create Thread In Java ?

 How To Create Thread In Java ? We can create thread in two ways : 1.By Extending Thread Class 2.By Implementing Runnable Interface. Example of Creating Thread By Extending Thread class : public class MyThread extends Thread { public static void main(String[] args) { MyThread thread1 = new MyThread(); thread1.start(); } @Override public void run() { System.out.println("Thread 1 is started"); } } Output: Thread 1 is started Example of Creating Thread by implementing Runnable Interface : public class ThreadDemo implements Runnable { public static void main(String[] args) { ThreadDemo td=new ThreadDemo(); Thread myThread=new Thread(td); myThread.start(); } @Override public void run() { System.out.println("Thread is started"); } } Output:   Thread is started

What is Method In Java

As we know Object is an entity with states and behavior , in java we are creating methods to represent behavior of object. Method is defined as group of instructions grouped together to perform a task, one of the biggest advantage of method is re-usability.we can create a method in java and we can call that method many times to perform some task.We do not need to write same code again and again.We can execute a method by calling or invoking it. One of the most important method in java is the main method ,execution of every java program , starts with main method : How to write main method in java ? public static void main(String[] args) { } Note - execution of every java program starts with main method. - we can create our own method to perform some set of operations : Method Signature In Java : syntax : AccessSpecifier ReturnType methodName (parameter1,parameter2){ } NOTE - Method Name should be in Camel Case Format : Example : addNumbers(),calculateInterest(),addition(), getEm...

this keyword in java

 this keyword in java refers to current object, where to use this keyword in java ? this keyword in java having multiple benefits and usage ,lets see one by one : 1.To Refer Current class instance variables   we can use this keyword in java Example :  step 1: firstly create a class Website.java as below  class Website{ String authorName; String websiteUrl; public Website(String authorName, String websiteUrl) { this.authorName = authorName; this.websiteUrl = websiteUrl; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getWebsiteUrl() { return websiteUrl; } public void setWebsiteUrl(String websiteUrl) { this.websiteUrl = websiteUrl; } @Override public String toString() { return "Website [authorName=" + authorName + ", websiteUrl=" + websiteUrl + "]"; } } Step 2 : create a class W...

Introduction to Java

Java is both a programming language and a platform , It is a high level language that is  simple ,object oriented, distributed, multithreaded, dynamic, architecture neutral, portable, robust  and secure. In the Java programming language, all source code is first written in plain text  files ending with the .java extension. Those source files are then compiled into .class files  by the Java compiler (javac). A .class file does not contain code that is native to a processor;  it instead contains bytecodes - the machine language of the Java Virtual Machine. The Java launcher tool (java) then runs the application with an instance of the Java Virtual Machine. The Java Virtual Machine is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris Operating System (Solaris OS), Linux, or MacOS. Some virtual machines,such as the Java HotSpot Virtual Machine, perform additional steps at runtime t...

Class and Object in Java

In Java we have to always deal with objects, now let's understand what is object , how to define object in Java. What is Object In Java ? Object is an entity with STATE and Behavior. Examples of Objects : Bike ,Mobile, Student,Laptop,Car etc. If we consider Bike As Object , Bike Name is state , Bike Color is state , and Running is behavior of Bike,Starting is behavior of bike and stopping is also behavior of Bike. In Java we say , Object is an Instance of class , it means we can create object using class. What is class ? A class is template or blueprint from which objects are created. A class in java can contain fields(variables),Methods(Behaviors),blocks,constructors etc. How To Create class in Java ? Syntax To Create Class :      class College {           String collegeName="COEP";           public void getAdmission(){           System.out.println("In this method we have to wri...

Setter Getter Vs Constructor

Firstly Understand these two examples , then read point below it : Example 1 : Here we are Using Setter Methods to initialize class level variable    Example 2: Here we are using Parameterized Constructor to create object and passing values as argument to constructor , the values which we will pass while creating object , those values will get assigned to particular object properties/variables.   Constructor is used to create , initialize object. When we use parameterized constructor to pass parameter it only call once. Means you can only pass parameter once. if you call it more then 1 time each time a new object created in memory. While getter and setter can be called according to your use many time to set or get values. In constructor , you can pass variables values as parameters then at object creation time those value will be assigned to instance variables. Where as in setter method : once the object is created then you can use it for setting up some value to it. It a...

Java Program To Filter List Data Using Lambda Expression

Identifier In Java

Identifier In Java :  -used for identification purpose. -name in java program is called identifier. - It can be class name, Method name ,variable name. Example : class CollegeManagement{                public static void main(String[] args){                     String collegeName="RECOEM";                } } In above program , identifiers are : 1.name of the class -> CollegeManagement 2.name of method -> main 3.name of class -> String 4.name of array -> args 5.name of variable -> collegeName Rules for defining Identifier : -allowed characters in Java Idenfier : a to z A to Z 0 to 9 $ _   NOTE -identifier will never start with number. -reserved words we cant use as identifiers, but we can used as predefined class name or interface name as Identifier ,but it is not good practice. -Java identifiers are case - sensitiv...

Java Software Engineer RoadMap

How to Become a Software Engineer ? How To Start Career as a java programmer ? learn these things in a sequence and you can become a java software engineer in 6 month to 1 year : 1.Core Java 2.Jdbc,Servlet,Jsp 3.Spring ,Hibernate 4.Spring Boot Rest 5.Design Patterns 6.Algorithm and Microservices  

Why Java is not Pure Object Oriented Programming Language ?

In short, Java is not a pure object-oriented programming language .because it supports primitive data types. In a pure object-oriented language everything is an object and there are many things in Java that are not objects  for Example: primitive data types like char, short, int, long, float, double,  and different type of arithmetic, logical and bitwise operator like  -,+,  /, &&, ||,* etc. Java has been never considered 100% or pure object-oriented programming language. There are seven qualities of Pure Object Oriented Programming Language :  1. Encapsulation/Data Hiding 2. Inheritance 3. Polymorphism 4. Abstraction 5. All predefined types are objects 6. All operations are performed by sending messages to objects 7. All user-defined types are objects. Java don't have all these 7 qualities that's why its not Pure Object Oriented Programming Language.

Interview Sorting Program Using Stream Java 8

Output :

Lambda Expressions

Lambda Expression  As we have seen in our last article Functional interface is introduced in Java 8 to support Lambda expression. today we will understand lambda expression : Lambda expression implement Functional Interfaces , it save lot of code. Check Example : WITHOUT LAMBDA EXPRESSION : below is same example , but using lambda expression ,in this lot of code is saved as below Lambda expression is nothing but method without name , access modifier and return type , it contain 3 main parts : 1.Parenthesis ( ) for method arguments , it can be non-empty or empty as per requirement. 2.Arrow Symbol -> indicates lambda expression  (to link method parameters or parenthesis with body). 3.Body (use curly braces for multiple lines , or if only one statement is there then curly braces are optional)  Syntax :  1.Syntax without method arguments :    () -> { } 1.Syntax with arguments :    (a1,a2) -> { } Example :check one more example to understand l...