Java , basics of java programming, JVM, JRE, JDK detailed explanation. primitive datatype. this ppt explains the basic concepts of java clearly starting from variables to complex programmes. It has 55 slides which gives you better understanding
The document provides an overview of Java concepts including:
1. The structure of a basic Java program including the class, main method, and print statement.
2. Explanations of keywords like public, static, void and how the main method works.
3. A description of Java APIs and how prewritten classes and packages are used.
4. Details on Java identifiers, variables, primitive and reference data types.
The document discusses Java programming concepts like comments, classes, methods, and user input. It provides explanations and examples of:
1) How comments are used in Java and the different types of comments.
2) The basic structure of a Java class including the main method that acts as the entry point.
3) How the System.out.println method prints output and how user input can be accepted using the Scanner class.
Java is an object-oriented programming language and platform. It uses a virtual machine (JVM) to run bytecode, making Java programs platform independent. The JVM handles memory management through garbage collection. Java uses classes and objects to implement OOP concepts. Variables are declared with a specific primitive data type or class type. Java supports control flow statements like if/else and loops. Arrays allow storing multiple values of the same type. Methods define reusable blocks of code that can operate on objects.
The document discusses various Java programming concepts including comments, identifiers, keywords, primitive data types, variables, objects, and access modifiers. It provides examples and definitions for each concept. The key points covered are the eight primitive data types in Java (boolean, char, byte, short, int, long, float, double), how to declare and initialize variables, how to construct objects using the new keyword, and the differences between public, private, protected, default, final, and abstract access modifiers.
This document provides an overview of object-oriented programming fundamentals in Java, including basic concepts like objects, classes, inheritance, polymorphism, and encapsulation. It discusses Java features, the Java program structure, variables and data types, operators, expressions, arrays, and control statements. Object-oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism are explained. The benefits and applications of OOP are also highlighted.
This document provides an overview of key Java concepts including: a brief history of Java; its platform independence and security features; data types like primitive, non-primitive, and reference types; variables and their scope; control structures like loops; methods and parameters/arguments; and classes. It discusses Java naming conventions and provides examples of basic Java code constructs like loops, variables, and methods.
This is a beginner-level programming session where you will learn the fundamentals of Java. Between each lesson, you'll have skill testing in the form of quizzes, as well as hands-on experience in the field.
Java is a widely used programming language that was created in 1991. It is an object-oriented language that is platform independent and runs on a virtual machine. Key features of Java include being simple, object-oriented, robust, secure, and portable. The Java runtime environment includes the Java virtual machine which executes Java bytecode. Common uses of Java include developing desktop and web applications, mobile apps, and embedded systems.
Enumerations, autoboxing, and annotations are discussed in the document. Enums allow defining a group of named constants and are commonly used to represent sets of values like months or types of beers. Autoboxing automatically converts between primitive types and their wrapper classes, making it easier to use primitives in object-oriented code. Annotations provide metadata about programs and can be used to annotate methods, classes, and other code elements. Retention policies determine when annotations are available during compilation and runtime.
1. In Java, all variable values are either primitives or references to objects. References are passed by value, so changes to referenced objects are visible outside method calls.
2. Java does not allow pointer arithmetic or dereferencing like in C++. References handle object access automatically.
3. Polymorphism in Java includes method overriding, overloading, and dynamic binding which allows subclasses to provide specific implementations of methods at runtime.
1. In Java, all variable values are either primitives or references to objects. References are passed by value, so changes to referenced objects are visible outside method calls.
2. Java does not allow pointer arithmetic or dereferencing like in C++. References handle object access automatically.
3. Polymorphism in Java includes method overriding, overloading, and dynamic binding which allows subclasses to provide specific implementations of methods at runtime.
This document provides an overview of Java basics including where Java is used, its key features, object-oriented programming concepts, platform independence, the structure of a basic Java program, variable types, operators, naming conventions, and constructors. Java is commonly used in desktop applications, web applications, enterprise applications, mobile apps, embedded systems, and more. It is a simple, secure, robust, portable, and interpreted language that is object-oriented, platform independent and supports multithreading. The document defines classes, inheritance, polymorphism, abstraction, and encapsulation. It also explains Java data types, variables, operators, and naming conventions. Constructors are special methods used to initialize objects that are invoked during object creation.
The document provides an overview of advanced class features in Java, including method overloading, overriding, and constructors. It discusses the differences between overloaded and overridden methods, and how to call parent class methods using super. It also covers enumerations, wrapper classes, autoboxing/unboxing, annotations, and inner classes.
Java is software programming language that rules the software world during 1995 to till date. It is an evergreen programming language. Internet flourished with java.
The document outlines an agenda for learning core Java concepts over 15 sections. It introduces key Java topics like primitive data types, variables, arrays, control flow statements, classes and objects, inheritance, polymorphism, exceptions, strings and characters, files and streams, and generic collections. The agenda also covers defining classes and methods, passing arguments, encapsulation, and memory concepts like objects, references, and the heap.
This document discusses Java variables, data types, and operators. It covers the basics of declaring variables in Java, including primitive and non-primitive data types. It also describes different types of variables, literals, casting, and operators such as arithmetic, assignment, comparison, and logical operators. Examples are provided to demonstrate variable declaration and usage of various operators.
Introduction to Annotations.
What are Annotations➔ Annotations are structured information added to program source code➔ Annotations associated meta-information with definitions➔ They can be attached to any variable, method, expression, or another program element Like comments, they can be sprinkled throughout a program➔ Unlike comments, they have structure, thus making them easier to machine process.
This document provides an introduction to the Java programming language concepts covered in the CAP615: Programming in Java course. It discusses computer programs and the Java language features like being easy to develop, platform independent, portable, multithreaded, distributed and object oriented. It also covers Java development environment, running and testing programs, classes and objects, defining fields and methods, variables, strings, numbers, operators, if/else statements and loops.
This document provides an overview of key Java concepts including: a brief history of Java; its platform independence and security features; data types like primitive, non-primitive, and reference types; variables and their scope; control structures like loops; methods and parameters/arguments; and classes. It discusses Java naming conventions and provides examples of basic Java code constructs like loops, variables, and methods.
This is a beginner-level programming session where you will learn the fundamentals of Java. Between each lesson, you'll have skill testing in the form of quizzes, as well as hands-on experience in the field.
Java is a widely used programming language that was created in 1991. It is an object-oriented language that is platform independent and runs on a virtual machine. Key features of Java include being simple, object-oriented, robust, secure, and portable. The Java runtime environment includes the Java virtual machine which executes Java bytecode. Common uses of Java include developing desktop and web applications, mobile apps, and embedded systems.
Enumerations, autoboxing, and annotations are discussed in the document. Enums allow defining a group of named constants and are commonly used to represent sets of values like months or types of beers. Autoboxing automatically converts between primitive types and their wrapper classes, making it easier to use primitives in object-oriented code. Annotations provide metadata about programs and can be used to annotate methods, classes, and other code elements. Retention policies determine when annotations are available during compilation and runtime.
1. In Java, all variable values are either primitives or references to objects. References are passed by value, so changes to referenced objects are visible outside method calls.
2. Java does not allow pointer arithmetic or dereferencing like in C++. References handle object access automatically.
3. Polymorphism in Java includes method overriding, overloading, and dynamic binding which allows subclasses to provide specific implementations of methods at runtime.
1. In Java, all variable values are either primitives or references to objects. References are passed by value, so changes to referenced objects are visible outside method calls.
2. Java does not allow pointer arithmetic or dereferencing like in C++. References handle object access automatically.
3. Polymorphism in Java includes method overriding, overloading, and dynamic binding which allows subclasses to provide specific implementations of methods at runtime.
This document provides an overview of Java basics including where Java is used, its key features, object-oriented programming concepts, platform independence, the structure of a basic Java program, variable types, operators, naming conventions, and constructors. Java is commonly used in desktop applications, web applications, enterprise applications, mobile apps, embedded systems, and more. It is a simple, secure, robust, portable, and interpreted language that is object-oriented, platform independent and supports multithreading. The document defines classes, inheritance, polymorphism, abstraction, and encapsulation. It also explains Java data types, variables, operators, and naming conventions. Constructors are special methods used to initialize objects that are invoked during object creation.
The document provides an overview of advanced class features in Java, including method overloading, overriding, and constructors. It discusses the differences between overloaded and overridden methods, and how to call parent class methods using super. It also covers enumerations, wrapper classes, autoboxing/unboxing, annotations, and inner classes.
Java is software programming language that rules the software world during 1995 to till date. It is an evergreen programming language. Internet flourished with java.
The document outlines an agenda for learning core Java concepts over 15 sections. It introduces key Java topics like primitive data types, variables, arrays, control flow statements, classes and objects, inheritance, polymorphism, exceptions, strings and characters, files and streams, and generic collections. The agenda also covers defining classes and methods, passing arguments, encapsulation, and memory concepts like objects, references, and the heap.
This document discusses Java variables, data types, and operators. It covers the basics of declaring variables in Java, including primitive and non-primitive data types. It also describes different types of variables, literals, casting, and operators such as arithmetic, assignment, comparison, and logical operators. Examples are provided to demonstrate variable declaration and usage of various operators.
Introduction to Annotations.
What are Annotations➔ Annotations are structured information added to program source code➔ Annotations associated meta-information with definitions➔ They can be attached to any variable, method, expression, or another program element Like comments, they can be sprinkled throughout a program➔ Unlike comments, they have structure, thus making them easier to machine process.
This document provides an introduction to the Java programming language concepts covered in the CAP615: Programming in Java course. It discusses computer programs and the Java language features like being easy to develop, platform independent, portable, multithreaded, distributed and object oriented. It also covers Java development environment, running and testing programs, classes and objects, defining fields and methods, variables, strings, numbers, operators, if/else statements and loops.
☁️ GDG Cloud Munich: Build With AI Workshop - Introduction to Vertex AI! ☁️
Join us for an exciting #BuildWithAi workshop on the 28th of April, 2025 at the Google Office in Munich!
Dive into the world of AI with our "Introduction to Vertex AI" session, presented by Google Cloud expert Randy Gupta.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
How to use nRF24L01 module with ArduinoCircuitDigest
Learn how to wirelessly transmit sensor data using nRF24L01 and Arduino Uno. A simple project demonstrating real-time communication with DHT11 and OLED display.
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
The role of the lexical analyzer
Specification of tokens
Finite state machines
From a regular expressions to an NFA
Convert NFA to DFA
Transforming grammars and regular expressions
Transforming automata to grammars
Language for specifying lexical analyzers
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
Ad
Java Tokens in java program . pptx
1. Java Tokens
• These statements and expressions are made up of tokens.
In other words, we can say that the expression and
statement is a set of token
• The Java compiler breaks the line of code into text (words) is
called Java tokens. These are the smallest element of the
Java program
2. • public class Demo
• {
• public static void main(String args[])
• {
• System.out.println("javatpoint");
• }
• }
• In the above code snippet, public, class, Demo, {, static, void, main, (, String,
args, [, ], ), System, ., out, println, javatpoint, etc. are the Java tokens.
3. • Java token includes the following:
• Keywords
• Identifiers
• Literals
• Operators
• Separators
• Comments
4. • Keywords: These are the pre-defined reserved words of any
programming language. Each keyword has a special
meaning. It is always written in lower case.
• Java provides the following keywords:
5. • Data Types in Java
• Data types specify the different sizes and values that can be
stored in the variable. There are two types of data types in
Java:
1.Primitive data types: The primitive data types include
boolean, char, byte, short, int, long, float and double.
2.Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
6. • Literals: In programming literal is a notation that represents a
fixed value (constant) in the source code.
• It can be categorized as an integer literal, string literal, Boolean
literal, etc. It is defined by the programmer.
• Once it has been defined cannot be changed.
• Java provides five types of literals are as follows:
• Integer
• Floating Point
• Character
• String
• Boolean
9. Operators: In operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators
that can be classified according to the functionality they provide.
• Arithmetic Operators
• Assignment Operators
• Relational Operators
• Unary Operators
• Logical Operators
• Ternary Operators
• Bitwise Operators
• Shift Operators
11. • Square Brackets []: It is used to define array elements. A pair of square
brackets represents the single-dimensional array, two pairs of square brackets
represent the two-dimensional array.
• Parentheses (): It is used to call the functions and parsing the parameters.
• Curly Braces {}: The curly braces denote the starting and ending of a code
block.
• Comma (,): It is used to separate two values, statements, and parameters.
• Assignment Operator (=): It is used to assign a variable and constant.
• Semicolon (;): It is the symbol that can be found at end of the statements. It
separates the two statements.
• Period (.): It separates the package name form the sub-packages and class. It
also separates a variable or method from a reference variable.
• Comments: Comments allow us to specify information about the program
inside our Java code. Java compiler recognizes these comments as tokens but
excludes it form further processing. The Java compiler treats comments as
whitespaces. Java provides the following two types of comments:
• Line Oriented: It begins with a pair of forwarding slashes (//).
• Block-Oriented: It begins with /* and continues until it founds */.
12. Java Constant
•a constant is an entity in programming that is
immutable. In other words, the value that cannot
be change.
•Constants can be declared using Java's static and
final keywords
•The static keyword is used for memory
management,
• and the final keyword signifies the property that
the variable's value cannot be changed
• It makes the primitive data types immutable.
•According to the Java naming convention the
identifier name must be in capital letters.
13. • Static and Final Modifiers
• The purpose to use the static modifier is to manage the
memory.
• It also allows the variable to be available without loading
any instance of the class in which it is defined.
• The final modifier represents that the value of the variable
cannot be changed. It also makes the primitive data
type immutable or unchangeable.
14. • Syntax for Java Constants
• static final datatype identifier_name = constant;
• Example:
• static final float PI = 3.14f;
15. • public class Declaration {
• static final double PI = 3.14;
• public static void main(String[] args) {
• System.out.println("Value of PI: " + PI);
• }
• }
16. • Declaring Constant as Private
• Using the private access modifier before the constant name
makes it inaccessible from other classes. It means the value
of the constant can be accessed from within the class only.
17. • class ClassA {
• private static final double PI = 3.14;
• }
• public class ClassB {
• public static void main(String[] args) {
• System.out.println("Value of PI: " + ClassA.PI);
• }
• }
18. • Declaring Constant as Public
• Using the public access modifier before the constant name makes it
available anywhere in the program.
• class ClassA {
• public static final double PI = 3.14;
• }
• public class ClassB {
• public static void main(String[] args) {
• System.out.println("Value of PI: " + ClassA.PI);
• }
• }
19. • Constants using Enumeration- Enum
• The Enumeration is created using the enum keyword in Java.
• The Enumeration in Java is a list of named constants.
• It is a datatype that contains a fixed number of constants. It
cannot be changed at runtime or dynamically.
• It is similar to that of the final variables in Java.
• It is used for defining class types in Java. Using enumeration
in class, the class can have constructor, methods, and
instance variables.
20. enum Car {
KIA,
Nano,
Maruti,
}
class EnumTest
{
public static void main(String args[])
{
Car c;
c = Car.Nano;
System.out.println("Value of c: " + c);
switch (c) {
case Maruti:
System.out.println("Maruti car");
break;
case KIA:
System.out.println("KIA car");
break;
case Nano:
System.out.println("Nano car");
break;
}
}
}
21. • Java Variables
• A variable is a container which holds the value while the
Java program is executed. A variable is assigned with a data
type.
• Variable is a name of memory location
• A variable is the name of a reserved area allocated in
memory
• int data=10;//Here data is variable
22. • Types of Variables
• There are three types of variables in Java:
• local variable
• instance variable
• static variable
23. • Local Variable
• A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
• A local variable cannot be defined with "static" keyword.
• 2) Instance Variable
• A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
• It is called an instance variable because its value is instance-specific and is not shared among
instances.
• 3) Static variable
• A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.
24. public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
A a=new A(); // a instance variable
a.method();
}
}//end of clas
25. • Java Simple for Loop
• A simple for loop is the same as C/C++. We can initialize the variable,
check condition and increment/decrement value. It consists of four
parts:
1.Initialization: It is the initial condition which is executed once when
the loop starts. Here, we can initialize the variable, or we can use an
already initialized variable. It is an optional condition.
2.Condition: It is the second condition which is executed each time to
test the condition of the loop. It continues execution until the
condition is false. It must return boolean value either true or false. It
is an optional condition.
3.Increment/Decrement: It increments or decrements the variable
value. It is an optional condition.
4.Statement: The statement of the loop is executed each time until
the second condition is false.
27. Example:
ForExample.java
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
28. • Java Nested for Loop
• If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever
outer loop executes.
Example:
NestedForExample.java
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
29. PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
30. public class PyramidExample2 {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
31. public class Main {
public static void main(String[] args) {
char last = 'E', alphabet = 'A';
for (int i = 1; i <= (last - 'A' + 1); ++i) {
for (int j = 1; j <= i; ++j) {
System.out.print(alphabet + " ");
}
++alphabet;
System.out.println();
}
}
}
32. Example 2: Program to print half
pyramid a using numbers
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
• public class Main {
• public static void main(String[] args) {
• int rows = 5;
• for (int i = 1; i <= rows; ++i) {
• for (int j = 1; j <= i; ++j) {
• System.out.print(j + " ");
• }
• System.out.println();
• }
• }
• }
33. • Example 4: Inverted half
pyramid using *
* * * * *
* * * *
* * *
* *
*
Source Code
public class Main {
public static void main(String[] args) {
int rows = 5;
for (int i = rows; i >= 1; --i) {
for (int j = 1; j <= i; ++j) {
System.out.print("* ");
}
System.out.println();
}
}
}
34. Example 5: Inverted half pyramid
using numbers
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Source Code
public class Main {
public static void main(String[] args) {
int rows = 5;
for (int i = rows; i >= 1; --i) {
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
35. Example 6: Program to print full pyramid using *
public class Pyramid {
public static void main(String[] args) {
int rows = 5, k = 0;
for (int i = 1; i <= rows; ++i, k = 0) {
for (int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
}
while (k != 2 * i - 1) {
System.out.print("* ");
++k;
}
System.out.println();
}
}
}
36. Example 7: Program to print pyramid using numbers
public class Main {
public static void main(String[] args) {
int rows = 5, k = 0, count = 0, count1 = 0;
for (int i = 1; i <= rows; ++i) {
for (int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
++count;
}
while (k != 2 * i - 1) {
if (count <= rows - 1) {
System.out.print((i + k) + " ");
++count;
} else {
++count1;
System.out.print((i + k - 2 * count1) + " ");
}
++k;
}
count1 = count = k = 0;
System.out.println();
}
}
}
37. • Java for-each Loop
• The for-each loop is used to traverse array or collection in Java. It
is easier to use than simple for loop because we don't need to
increment value and use subscript notation.
• It works on the basis of elements and not the index. It returns
element one by one in the defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
38. ForEachExample.java
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
39. • Java Labeled For Loop
• We can have a name of each Java for loop. To do so, we use label
before the for loop. It is useful while using the nested for loop as
we can break/continue specific for loop.
Syntax:
labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}
40. LabeledForExample.java
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
•
If you use break bb;, it will break inner loop only which is the default behaviour of any loop.
41. public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
42. • What is a Switch Case in Java?
• Switch case in Java is essential for avoiding redundant if-else statements in a
program.
switch(variable_name)
{
case value1:
//code to be executed if variable_name=value1
break;
case value2:
//code to be executed if variable_name=value2
break;
default:
//code to be executed if variable_name=value3
}
43. package com.dataflair.switchcase;
import java.util.*;
public class SwitchStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int variable;
System.out.println("Please enter the variable
value 1,2,3 ");
variable=sc.nextInt();
switch(variable)
{
case 1:
System.out.println("The value of the variable = "+variable);
break;
case 2:
System.out.println("The value of the variable ="+variable);
break;
case 3:
System.out.println("The value of the variable ="+variable);
break;
default:
System.out.println("The value of the variable is neither 1
nor 2 nor 3");
}
}
}
44. package com.dataflair.switchcase;
import java.util.*;
public class SwitchStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int variable;
System.out.println("Please enter the
variable value");
variable=sc.nextInt();
switch(variable)
{
case 1:
System.out.println("The value of the
variable = "+variable);
case 2:
System.out.println("The value of the
variable = "+variable);
case 3:
System.out.println("Value of the variable =
"+variable);
default:
• System.out.println("The value of the
variable is neither 1 nor 2 nor 3");
• }
• }
• }
45. package com.dataflair.java.switchcase;
public class SwitchStrings
{
public static void main(String[] args) {
String course="java";
switch(course)
{
case "python":
System.out.println("Python was made by Guido Van Rossum");
break;
case "java":
System.out.println("Java was made by James Gosling! It is one of Shraman's favourites!");
break;
case "c++":
System.out.println("C ++ was made by Bjarne Stroustrup");
break;
}
}
}
46. package com.dataflair.switchcase;
import java.util.*;
public class NestedSwitch
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String course="java";
switch(course)
{
case "python":
System.out.println("Python was made by Guido Van
Rossum");
break;
case "java":
System.out.println("What version of Java are you
using?");
int version=sc.nextInt();
switch(version)
{
case 6:
System.out.println("That is old school!");
break;
case 8:
System.out.println("Wow, that’s great! Tons of
new features!");
break;
}
break;
case "c++":
System.out.println("C ++ was made by Bjarne
Stroustrup");
break;
}
}
}
47. Java instanceof Operator
• The instanceof operator in Java is used to check whether an object is
an instance of a particular class or not.
49. // Java Program to check if an
object of the subclass
// is also an instance of the
superclass
// superclass
class Animal {
}
// subclass
class Dog extends Animal {
}
class Main {
public static void main(String[] args) {
// create an object of the subclass
Dog d1 = new Dog();
// checks if d1 is an instance of the
subclass
System.out.println(d1 instanceof
Dog); // prints true
// checks if d1 is an instance of the
superclass
System.out.println(d1 instanceof Animal); }
}
51. Dot Operator
• It is just a syntactic element. It denotes the separation of
class from a package, separation of method from the class,
and separation of a variable from a reference variable. It is
also known as separator or period or member operator.
It is used to separate a variable and method from a
reference variable.
It is also used to access classes and sub-packages from a
package.
It is also used to access the member of a package or a class.
52. public class DotOperatorExample1
{
void display()
{
double d = 67.54;
//casting double type to integer
int i = (int)d;
System.out.println(i);
}
public static void main(String args[])
{
DotOperatorExample1 doe = new DotOperatorExample1();
//method calling
doe.display();
}
}
53. Type Casting in Java
• In Java, type casting is a method or process that converts a
data type into another data type
• Two types
• manually - The automatic conversion is done by the
compiler
• automatically- manual conversion performed by the
programmer.
54. Widening or Automatic/Implicit Type Conversion
• Widening conversion takes place when two data types are
automatically converted.
• This happens when:
• The two data types are compatible.
• When we assign a value of a smaller data type to a bigger
data type.
• Converting a lower data type into a higher one is
called widening type casting.
• It is also known as implicit conversion or down casting
• It is safe because there is no chance to lose data
55. // Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
int i = 100;
// Automatic type conversion
// Integer to long type
long l = i;
// Automatic type conversion
// long to float type
float f = l;
// Print and display commands
System.out.println("Int value " +
i);
System.out.println("Long value " +
l);
System.out.println("Float value " + f);
56. Narrowing/Explicit/Up casting Type
Casting
• Converting a higher data type into a lower one is
called narrowing type casting
• It is also known as explicit conversion or casting up
• It is done manually by the programmer.
• If we do not perform casting then the compiler reports a
compile-time error.
57. // Java program to illustrate Incompatible data
Type
// for Explicit Type Conversion
// Main class
public class GFG {
// Main driver method
public static void main(String[] argv)
{
// Declaring character variable
char ch = 'c';
// Declaringinteger variable
int num = 88;
// Trying to insert integer to character
ch = num;
}
58. // Java program to Illustrate Explicit Type
Conversion
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully
getting
// data from long datatype to integer type
long l = (long)d;
// Explicit type casting
int i = (int)l;
// Print statements
System.out.println("Double value " + d);
// While printing we will see that
// fractional part lost
System.out.println("Long value " + l);
// While printing we will see that
59. // Print commands
System.out.println("i = " + i + "
b = " + b);
System.out.println(
"nConversion of double to
byte.");
// d % 256
b = (byte)d;
// Print commands
System.out.println("d = " + d + "
b= " + b);
}
}
/ Java Program to Illustrate Conversion of
// Integer and Double to Byte
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Declaring byte variable
byte b;
// Declaring and initializing integer and
double
int i = 257;
double d = 323.142;
// Display message
System.out.println("Conversion of int to
byte.");
// i % 256
b = (byte)i;
60. • Type Promotion in Expressions
• While evaluating expressions, the intermediate value may
exceed the range of operands and hence the expression
value will be promoted. Some conditions for type promotion
are:
1.Java automatically promotes each byte, short, or char
operand to int when evaluating an expression.
2.If one operand is long, float or double the whole expression
is promoted to long, float, or double respectively.
61. / Java program to Illustrate Type promotion in
Expressions
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Declaring and initializing primitive
types
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
// The Expression
double result = (f * b) + (i / c) - (d *
s);
// Printing the result obtained after
// all the promotions are done
62. • Explicit Type Casting in Expressions
• While evaluating expressions, the result is automatically
updated to a larger data type of the operand. But if we store
that result in any smaller data type it generates a compile-
time error, due to which we need to typecast the result.
63. // Java program to Illustrate Type
Casting
// in Integer to Byte
// Main class
class GFG {
// Main driver method
public static void main(String
args[])
{
// Declaring byte array
byte b = 50;
// Type casting int to byte
b = (byte)(b * 2);
// Display value in byte
System.out.println(b);
}
}
64. Mathematical Function-1) min():
public class min
{
public static void main(String
args[])
{
System.out.println(Math.min(12.12
3,12.456));
System.out.println(Math.min(23.12
,23.0));
}
}
65. sqrt()
public class sqrtf
{
public static void main(String
args[])
{
double y=11.635;
System.out.println(Math.sqrt(16));
System.out.println(Math.sqrt(y));
}
}
66. pow()
public class powf
{
public static void main(String args[])
{
int x=2,y=3;
double a=11.635,b=2.76;
System.out.println(Math.pow(x,y));
System.out.println(Math.pow(a,b));
}
}
67. public class roundf
{
public static void main(String args[])
{
double d=100.675;
double e=100.500;
float f=100;
float g=90f;
System.out.println(Math.round(d));
System.out.println(Math.round(e));
System.out.println(Math.round(f));
System.out.println(Math.round(g));
}
}
68. abs()
public class absf
{
public static void main(String args[])
{
int a=-8;
double d=-100;
float f=-90;
System.out.println(Math.abs(a));
System.out.println(Math.abs(d));
System.out.println(Math.abs(f));
}
}