SlideShare a Scribd company logo
1 of 12
Download to read offline
HelloWorld.java
Below is the syntax highlighted version of HelloWorld.java from §1.1 Hello World.



/*************************************************************************
 * Compilation: javac HelloWorld.java
 * Execution:     java HelloWorld
 *
 * Prints "Hello, World". By tradition, this is everyone's first program.
 *
 * % java HelloWorld
 * Hello, World
 *
 * These 17 lines of text are comments. They are not part of the program;
 * they serve to remind us about its properties. The first two lines tell
 * us what to type to compile and test the program. The next line describes
 * the purpose of the program. The next few lines give a sample execution
 * of the program and the resulting output. We will always include such
 * lines in our programs and encourage you to do the same.
 *
 *************************************************************************/

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}




                        UseArgument.java
Below is the syntax highlighted version of UseArgument.java from §1.1 Hello World.



/*************************************************************************
 * Compilation: javac UseArgument.java
 * Execution:     java UseArgument yourname
 *
 * Prints "Hi, Bob. How are you?" where "Bob" is replaced by the
 * command-line argument.
 *
 * % java UseArgument Bob
 * Hi, Bob. How are you?
*
    * % java UseArgument Alice
    * Hi, Alice. How are you?
    *
    *************************************************************************/

public class UseArgument {

       public static void main(String[] args) {
           System.out.print("Hi, ");
           System.out.print(args[0]);
           System.out.println(". How are you?");
       }

}
IntOps.java



/*************************************************************************
 * Compilation: javac IntOps.java
 * Execution:     java IntOps a b
 *
 * Illustrates the integer operations a * b, a / b, and a % b.
 *
 * % java IntOps 1234 99
 * 1234 + 99 = 1333
 * 1234 * 99 = 122166
 * 1234 / 99 = 12
 * 1234 % 99 = 46
 * 1234 = 12 * 99 + 46
 *
 * % java IntOps 10 -3
 * 10 + -3 = 7
 * 10 * -3 = -30
 * 10 / -3 = -3
 * 10 % -3 = 1
 * 10 = -3 * -3 + 1
 *
 *************************************************************************/

public class IntOps {

    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int sum = a + b;
        int prod = a * b;
        int quot = a / b;
        int rem = a % b;

        System.out.println(a   +   "   +   "   +   b + " = " + sum);
        System.out.println(a   +   "   *   "   +   b + " = " + prod);
        System.out.println(a   +   "   /   "   +   b + " = " + quot);
        System.out.println(a   +   "   %   "   +   b + " = " + rem);
        System.out.println(a   +   "   =   "   +   quot + " * " + b + " + " + rem);
    }
}
Quadratic.java
Below is the syntax highlighted version of Quadratic.java from §1.2 Built-in Types of Data.



/*************************************************************************
 * Compilation: javac Quadratic.java
 * Execution:     java Quadatic b c
 *
 * Given b and c, solves for the roots of x*x + b*x + c.
 * Assumes both roots are real valued.
 *
 * % java Quadratic -3.0 2.0
 * 2.0
 * 1.0
 *
 * % java Quadratic -1.0 -1.0
 * 1.618033988749895
 * -0.6180339887498949
 *
 * Remark: 1.6180339... is the golden ratio.
 *
 * % java Quadratic 1.0 1.0
 * NaN
 * NaN
 *
 *
 *************************************************************************/

public class Quadratic {

    public static void main(String[] args) {
        double b = Double.parseDouble(args[0]);
        double c = Double.parseDouble(args[1]);

         double discriminant = b*b - 4.0*c;
         double sqroot = Math.sqrt(discriminant);

         double root1 = (-b + sqroot) / 2.0;
         double root2 = (-b - sqroot) / 2.0;

         System.out.println(root1);
         System.out.println(root2);
    }
}
LeapYear.java
Below is the syntax highlighted version of LeapYear.java from §1.2 Built-in Types of Data.




/*************************************************************************
 * Compilation: javac LeapYear.java
 * Execution:     java LeapYear N
 *
 * Prints true if N corresponds to a leap year, and false otherwise.
 * Assumes N >= 1582, corresponding to a year in the Gregorian calendar.
 *
 * % java LeapYear 2004
 * true
 *
 * % java LeapYear 1900
 * false
 *
 * % java LeapYear 2000
 * true
 *
 *************************************************************************/

public class LeapYear {
    public static void main(String[] args) {
        int year = Integer.parseInt(args[0]);
        boolean isLeapYear;

         // divisible by 4
         isLeapYear = (year % 4 == 0);

         // divisible by 4 and not 100
         isLeapYear = isLeapYear && (year % 100 != 0);

         // divisible by 4 and not 100 unless divisible by 400
         isLeapYear = isLeapYear || (year % 400 == 0);

         System.out.println(isLeapYear);
    }
}
LeapYear.java



/*************************************************************************
 * Compilation: javac LeapYear.java
 * Execution:     java LeapYear N
 *
 * Prints true if N corresponds to a leap year, and false otherwise.
 * Assumes N >= 1582, corresponding to a year in the Gregorian calendar.
 *
 * % java LeapYear 2004
 * true
 *
 * % java LeapYear 1900
 * false
 *
 * % java LeapYear 2000
 * true
 *
 *************************************************************************/

public class LeapYear {
    public static void main(String[] args) {
        int year = Integer.parseInt(args[0]);
        boolean isLeapYear;

        // divisible by 4
        isLeapYear = (year % 4 == 0);

        // divisible by 4 and not 100
        isLeapYear = isLeapYear && (year % 100 != 0);

        // divisible by 4 and not 100 unless divisible by 400
        isLeapYear = isLeapYear || (year % 400 == 0);

        System.out.println(isLeapYear);
    }
}
Sqrt.java


/*************************************************************************
 * Compilation: javac Sqrt.java
 * Execution:     java Sqrt c
 *
 * Computes the square root of a nonnegative number c using
 * Newton's method:
 *     - initialize t = c
 *     - replace t with the average of c/t and t
 *     - repeat until desired accuracy reached
 *
 * % java Sqrt 2
 * 1.414213562373095
 *
 * % java Sqrt 1000000
 * 1000.0
 *
 * % java Sqrt 0.4
 * 0.6324555320336759
 *
 * % java Sqrt 1048575
 * 1023.9995117186336
 *
 * % java Sqrt 16664444
 * 4082.2106756021303
 *
 * % java Sqrt 0
 * 0.0
 *
 * % java Sqrt 1e-50
 * 9.999999999999999E-26
 *
 *
 * Remarks
 * ----------
 *   - using Math.abs() is required if c < 1
 *
 *
 * Known bugs
 * ----------
 *   - goes into an infinite loop if the input is negative
 *
 *************************************************************************/

public class Sqrt {
    public static void main(String[] args) {

       // read in the command-line argument
       double c = Double.parseDouble(args[0]);
double epsilon = 1e-15;    // relative error tolerance
        double t = c;              // estimate of the square root of c

        // repeatedly apply Newton update step until desired precision is
achieved
        while (Math.abs(t - c/t) > epsilon*t) {
            t = (c/t + t) / 2.0;
        }

        // print out the estimate of the square root of c
        System.out.println(t);
    }

}
Average.java



/*************************************************************************
 * Compilation: javac Average.java
 * Execution:     java Average < data.txt
 * Dependencies: StdIn.java StdOut.java
 *
 * Reads in a sequence of real numbers, and computes their average.
 *
 * % java Average
 * 10.0 5.0 6.0
 * 3.0 7.0 32.0
 * <Ctrl-d>
 * Average is 10.5

    * Note <Ctrl-d> signifies the end of file on Unix.
    * On windows use <Ctrl-z>.
    *
    *************************************************************************/

public class Average {
    public static void main(String[] args) {
        int count = 0;       // number input values
        double sum = 0.0;    // sum of input values

           // read data and compute statistics
           while (!StdIn.isEmpty()) {
               double value = StdIn.readDouble();
               sum += value;
               count++;
           }

           // compute the average
           double average = sum / count;

           // print results
           StdOut.println("Average is " + average);
       }
}
ArrayEquals.java
/************************************************************************

    * Compilation: javac ArrayEquals.java
    * Execution:     java ArrayEquals
    *
    * The function eq() takes two integer array arguments and returns
    * true if they have the same length and all corresponding pairs
    * of integers are equal.
    *
    * % java ArrayEquals
    * true
    * false
    * true
    * false
    *
    *************************************************************************/

public class ArrayEquals {

       // return true if two integer arrays have same length and all
       // corresponding pairs of integers are equal
       public static boolean eq(int[] a, int[] b) {

           // same length?
           if (a.length != b.length) return false;

           // check each corresponding pair
           for (int i = 0; i < a.length; i++) {
               if (a[i] != b[i]) return false;
           }

           // all elements must be equal
           return true;
       }


       // test client
       public static void   main(String[] args) {
           int[] a = { 3,   1, 4, 1, 5 };
           int[] b = { 3,   1, 4, 1 };
           int[] c = { 3,   1, 4, 1, 5 };
           int[] d = { 2,   7, 1, 8, 2 };

           StdOut.println(eq(a,   a));
           StdOut.println(eq(a,   b));
           StdOut.println(eq(a,   c));
           StdOut.println(eq(a,   d));
       }
}
WordCount.java
/*************************************************************************

    * Compilation: javac WordCount.java
    * Execution:     java WordCount
    *         [ input required from standard input                        ]
    *         [ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
    *
    * Dependencies: StdIn.java StdOut.java
    *
    * Read in a sequence of strings from standard input and print out
    * the number of strings read in.
    *
    * % java WordCount
    * it was the best of times
    * it was the worst of times
    * number of words = 12
    * Ctrl-d
    *
    * % java WordCount < tale.txt
    * number of words = 139043
    *
    *************************************************************************/

public class WordCount {
    public static void main(String[] args) {

           int count = 0;
           while (!StdIn.isEmpty()) {
               String word = StdIn.readString();
               count++;
           }

           // output
           StdOut.println("number of words   = " + count);
       }
}
RandomSeq.java


/*************************************************************************
 * Compilation: javac RandomSeq.java
 * Execution:     java RandomSeq N
 *
 * Prints N numbers between 0 and 1.
 *
 * % java RandomSeq 5
 * 0.1654760343787165
 * 0.6212262060326124
 * 0.631755596883274
 * 0.4165639935584283
 * 0.4603525361488371
 *
 *************************************************************************/

public class RandomSeq {
    public static void main(String[] args) {

        // command-line argument
        int N = Integer.parseInt(args[0]);

        // generate and print N numbers between 0 and 1
        for (int i = 0; i < N; i++) {
            System.out.println(Math.random());
        }
    }
}

More Related Content

What's hot

Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 
Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)Hongyang Wang
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivediharintrivedi
 
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...sachin kumar
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hypeMagdiel Duarte
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
An Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAn Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAndrey Karpov
 

What's hot (20)

Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Enumerable
EnumerableEnumerable
Enumerable
 
Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)Sql Injection Attacks(Part1 4)
Sql Injection Attacks(Part1 4)
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivedi
 
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
New text document
New text documentNew text document
New text document
 
Managing Mocks
Managing MocksManaging Mocks
Managing Mocks
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
An Experiment with Checking the glibc Library
An Experiment with Checking the glibc LibraryAn Experiment with Checking the glibc Library
An Experiment with Checking the glibc Library
 

Viewers also liked

25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROIAWeber
 
Get More Email Subscribers
Get More Email SubscribersGet More Email Subscribers
Get More Email SubscribersAWeber
 
Email List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple StepsEmail List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple StepsAWeber
 
Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)webhostingguy
 
Cyber crime ppt
Cyber crime pptCyber crime ppt
Cyber crime pptBushra22
 
Email Marketing Ppt Presentation
Email Marketing Ppt PresentationEmail Marketing Ppt Presentation
Email Marketing Ppt PresentationDiseño Domingo
 
Email Marketing Presentation
Email Marketing PresentationEmail Marketing Presentation
Email Marketing PresentationIain Davenport
 

Viewers also liked (7)

25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
25 List Building Tricks: Ideas, Examples and Resources to Improve Your Email ROI
 
Get More Email Subscribers
Get More Email SubscribersGet More Email Subscribers
Get More Email Subscribers
 
Email List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple StepsEmail List-Building 101: How to Reel In New Readers with a Few Simple Steps
Email List-Building 101: How to Reel In New Readers with a Few Simple Steps
 
Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)Symantec AntiSpam Complete Overview (PowerPoint)
Symantec AntiSpam Complete Overview (PowerPoint)
 
Cyber crime ppt
Cyber crime pptCyber crime ppt
Cyber crime ppt
 
Email Marketing Ppt Presentation
Email Marketing Ppt PresentationEmail Marketing Ppt Presentation
Email Marketing Ppt Presentation
 
Email Marketing Presentation
Email Marketing PresentationEmail Marketing Presentation
Email Marketing Presentation
 

Similar to Java code examples from Introduction to Programming in Java

Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2sotlsoc
 
(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdf(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdfrbjain2007
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 
Treatment, Architecture and Threads
Treatment, Architecture and ThreadsTreatment, Architecture and Threads
Treatment, Architecture and ThreadsMathias Seguy
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujeigersonjack
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docxransayo
 
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfg++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfarakalamkah11
 
URGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdfURGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdferremmfab
 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docxjanettjz6sfehrle
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the BasicsJussi Pohjolainen
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02auswhit
 

Similar to Java code examples from Introduction to Programming in Java (20)

Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2
 
(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdf(In java language)1. Use recursion in implementing the binarySearc.pdf
(In java language)1. Use recursion in implementing the binarySearc.pdf
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
Java Print method
Java  Print methodJava  Print method
Java Print method
 
Treatment, Architecture and Threads
Treatment, Architecture and ThreadsTreatment, Architecture and Threads
Treatment, Architecture and Threads
 
Vo.pdf
   Vo.pdf   Vo.pdf
Vo.pdf
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
 
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfg++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
 
URGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdfURGENTJavaPlease updated the already existing Java program and m.pdf
URGENTJavaPlease updated the already existing Java program and m.pdf
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docx
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02
 

Recently uploaded

Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 

Recently uploaded (20)

Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 

Java code examples from Introduction to Programming in Java

  • 1. HelloWorld.java Below is the syntax highlighted version of HelloWorld.java from §1.1 Hello World. /************************************************************************* * Compilation: javac HelloWorld.java * Execution: java HelloWorld * * Prints "Hello, World". By tradition, this is everyone's first program. * * % java HelloWorld * Hello, World * * These 17 lines of text are comments. They are not part of the program; * they serve to remind us about its properties. The first two lines tell * us what to type to compile and test the program. The next line describes * the purpose of the program. The next few lines give a sample execution * of the program and the resulting output. We will always include such * lines in our programs and encourage you to do the same. * *************************************************************************/ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } UseArgument.java Below is the syntax highlighted version of UseArgument.java from §1.1 Hello World. /************************************************************************* * Compilation: javac UseArgument.java * Execution: java UseArgument yourname * * Prints "Hi, Bob. How are you?" where "Bob" is replaced by the * command-line argument. * * % java UseArgument Bob * Hi, Bob. How are you?
  • 2. * * % java UseArgument Alice * Hi, Alice. How are you? * *************************************************************************/ public class UseArgument { public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args[0]); System.out.println(". How are you?"); } }
  • 3. IntOps.java /************************************************************************* * Compilation: javac IntOps.java * Execution: java IntOps a b * * Illustrates the integer operations a * b, a / b, and a % b. * * % java IntOps 1234 99 * 1234 + 99 = 1333 * 1234 * 99 = 122166 * 1234 / 99 = 12 * 1234 % 99 = 46 * 1234 = 12 * 99 + 46 * * % java IntOps 10 -3 * 10 + -3 = 7 * 10 * -3 = -30 * 10 / -3 = -3 * 10 % -3 = 1 * 10 = -3 * -3 + 1 * *************************************************************************/ public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); System.out.println(a + " = " + quot + " * " + b + " + " + rem); } }
  • 4. Quadratic.java Below is the syntax highlighted version of Quadratic.java from §1.2 Built-in Types of Data. /************************************************************************* * Compilation: javac Quadratic.java * Execution: java Quadatic b c * * Given b and c, solves for the roots of x*x + b*x + c. * Assumes both roots are real valued. * * % java Quadratic -3.0 2.0 * 2.0 * 1.0 * * % java Quadratic -1.0 -1.0 * 1.618033988749895 * -0.6180339887498949 * * Remark: 1.6180339... is the golden ratio. * * % java Quadratic 1.0 1.0 * NaN * NaN * * *************************************************************************/ public class Quadratic { public static void main(String[] args) { double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]); double discriminant = b*b - 4.0*c; double sqroot = Math.sqrt(discriminant); double root1 = (-b + sqroot) / 2.0; double root2 = (-b - sqroot) / 2.0; System.out.println(root1); System.out.println(root2); } }
  • 5. LeapYear.java Below is the syntax highlighted version of LeapYear.java from §1.2 Built-in Types of Data. /************************************************************************* * Compilation: javac LeapYear.java * Execution: java LeapYear N * * Prints true if N corresponds to a leap year, and false otherwise. * Assumes N >= 1582, corresponding to a year in the Gregorian calendar. * * % java LeapYear 2004 * true * * % java LeapYear 1900 * false * * % java LeapYear 2000 * true * *************************************************************************/ public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 isLeapYear = (year % 4 == 0); // divisible by 4 and not 100 isLeapYear = isLeapYear && (year % 100 != 0); // divisible by 4 and not 100 unless divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } }
  • 6. LeapYear.java /************************************************************************* * Compilation: javac LeapYear.java * Execution: java LeapYear N * * Prints true if N corresponds to a leap year, and false otherwise. * Assumes N >= 1582, corresponding to a year in the Gregorian calendar. * * % java LeapYear 2004 * true * * % java LeapYear 1900 * false * * % java LeapYear 2000 * true * *************************************************************************/ public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 isLeapYear = (year % 4 == 0); // divisible by 4 and not 100 isLeapYear = isLeapYear && (year % 100 != 0); // divisible by 4 and not 100 unless divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } }
  • 7. Sqrt.java /************************************************************************* * Compilation: javac Sqrt.java * Execution: java Sqrt c * * Computes the square root of a nonnegative number c using * Newton's method: * - initialize t = c * - replace t with the average of c/t and t * - repeat until desired accuracy reached * * % java Sqrt 2 * 1.414213562373095 * * % java Sqrt 1000000 * 1000.0 * * % java Sqrt 0.4 * 0.6324555320336759 * * % java Sqrt 1048575 * 1023.9995117186336 * * % java Sqrt 16664444 * 4082.2106756021303 * * % java Sqrt 0 * 0.0 * * % java Sqrt 1e-50 * 9.999999999999999E-26 * * * Remarks * ---------- * - using Math.abs() is required if c < 1 * * * Known bugs * ---------- * - goes into an infinite loop if the input is negative * *************************************************************************/ public class Sqrt { public static void main(String[] args) { // read in the command-line argument double c = Double.parseDouble(args[0]);
  • 8. double epsilon = 1e-15; // relative error tolerance double t = c; // estimate of the square root of c // repeatedly apply Newton update step until desired precision is achieved while (Math.abs(t - c/t) > epsilon*t) { t = (c/t + t) / 2.0; } // print out the estimate of the square root of c System.out.println(t); } }
  • 9. Average.java /************************************************************************* * Compilation: javac Average.java * Execution: java Average < data.txt * Dependencies: StdIn.java StdOut.java * * Reads in a sequence of real numbers, and computes their average. * * % java Average * 10.0 5.0 6.0 * 3.0 7.0 32.0 * <Ctrl-d> * Average is 10.5 * Note <Ctrl-d> signifies the end of file on Unix. * On windows use <Ctrl-z>. * *************************************************************************/ public class Average { public static void main(String[] args) { int count = 0; // number input values double sum = 0.0; // sum of input values // read data and compute statistics while (!StdIn.isEmpty()) { double value = StdIn.readDouble(); sum += value; count++; } // compute the average double average = sum / count; // print results StdOut.println("Average is " + average); } }
  • 10. ArrayEquals.java /************************************************************************ * Compilation: javac ArrayEquals.java * Execution: java ArrayEquals * * The function eq() takes two integer array arguments and returns * true if they have the same length and all corresponding pairs * of integers are equal. * * % java ArrayEquals * true * false * true * false * *************************************************************************/ public class ArrayEquals { // return true if two integer arrays have same length and all // corresponding pairs of integers are equal public static boolean eq(int[] a, int[] b) { // same length? if (a.length != b.length) return false; // check each corresponding pair for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } // all elements must be equal return true; } // test client public static void main(String[] args) { int[] a = { 3, 1, 4, 1, 5 }; int[] b = { 3, 1, 4, 1 }; int[] c = { 3, 1, 4, 1, 5 }; int[] d = { 2, 7, 1, 8, 2 }; StdOut.println(eq(a, a)); StdOut.println(eq(a, b)); StdOut.println(eq(a, c)); StdOut.println(eq(a, d)); } }
  • 11. WordCount.java /************************************************************************* * Compilation: javac WordCount.java * Execution: java WordCount * [ input required from standard input ] * [ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ] * * Dependencies: StdIn.java StdOut.java * * Read in a sequence of strings from standard input and print out * the number of strings read in. * * % java WordCount * it was the best of times * it was the worst of times * number of words = 12 * Ctrl-d * * % java WordCount < tale.txt * number of words = 139043 * *************************************************************************/ public class WordCount { public static void main(String[] args) { int count = 0; while (!StdIn.isEmpty()) { String word = StdIn.readString(); count++; } // output StdOut.println("number of words = " + count); } }
  • 12. RandomSeq.java /************************************************************************* * Compilation: javac RandomSeq.java * Execution: java RandomSeq N * * Prints N numbers between 0 and 1. * * % java RandomSeq 5 * 0.1654760343787165 * 0.6212262060326124 * 0.631755596883274 * 0.4165639935584283 * 0.4603525361488371 * *************************************************************************/ public class RandomSeq { public static void main(String[] args) { // command-line argument int N = Integer.parseInt(args[0]); // generate and print N numbers between 0 and 1 for (int i = 0; i < N; i++) { System.out.println(Math.random()); } } }